How exactly does document.cookie work?

岁酱吖の 提交于 2019-11-27 05:39:34

问题


If I get Chrome to show me document.cookie by going into the console and typing document.cookie; it'll give me, say:

"name=John; gender=male";

But then if I type in, say, document.cookie = 5; all it does is add 5; to the start of the string, so I get:

"5; name=John; gender=male";

If I try document.cookie = null; then it doesn't even do anything.

How can this be? It's a variable, isn't it? So why isn't the assignment operator working the way it should? Is it actually just a bit of syntactic sugar rather than a real variable? And if so, what precisely is the sugar covering up?


回答1:


document.cookie has very special behavior. As you've seen, assigning to it adds (or updates) a cookie (or multiple cookies), rather than replacing all of the cookies. It's very unusual.

Read all about it on MDN.




回答2:


Why not have a look at MDN?

The string on the right side of the assignment operator to document.cookies should be a semicolon separated list of key-value pairs, i.e. document.cookie = "aKey=5" will set/update the aKey cookie.

So yes, document.cookie shows special behavior.




回答3:


Here is an example of your "issue". Also, it says the following:

You can delete a cookie by simply updating its expiration time to zero.



来源:https://stackoverflow.com/questions/6791944/how-exactly-does-document-cookie-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!