Javascript document.cookie 究竟是如何工作的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6791944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How exactly does document.cookie work?
提问by Hyman M
If I get Chrome to show me document.cookie
by going into the console and typing document.cookie;
it'll give me, say:
如果我document.cookie
通过进入控制台并输入document.cookie;
它来让 Chrome 向我展示,它会给我,说:
"name=John; gender=male";
"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:
但是如果我输入,比如说,document.cookie = 5;
它所做的就是添加5;
到字符串的开头,所以我得到:
"5; name=John; gender=male";
"5; name=John; gender=male";
If I try document.cookie = null;
then it doesn't even do anything.
如果我尝试,document.cookie = null;
它甚至不会做任何事情。
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?
怎么会这样?这是一个变量,不是吗?那么为什么赋值运算符没有按照它应该的方式工作呢?它实际上只是一些语法糖而不是真正的变量吗?如果是这样,糖究竟掩盖了什么?
采纳答案by T.J. Crowder
document.cookie
has veryspecial behavior. As you've seen, assigning to it adds(or updates) a cookie (or multiple cookies), rather than replacingall of the cookies. It's very unusual.
document.cookie
有非常特殊的行为。如您所见,分配给它会添加(或更新)一个 cookie(或多个 cookie),而不是替换所有 cookie。这是非常不寻常的。
Read all about it on MDN.
在MDN上阅读所有相关信息。
回答by Alexander Gessler
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.
赋值运算符 to 右侧的字符串document.cookies
应该是一个以分号分隔的键值对列表,document.cookie = "aKey=5"
即将设置/更新aKey
cookie。
So yes, document.cookie
shows special behavior.
所以是的,document.cookie
表现出特殊的行为。