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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:12:06  来源:igfitidea点击:

How exactly does document.cookie work?

javascriptdebugginggoogle-chromejavascript-debugger

提问by Hyman M

If I get Chrome to show me document.cookieby 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.cookiehas 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

Why not have a look at MDN?

为什么不看看 MDN?

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

赋值运算符 to 右侧的字符串document.cookies应该是一个以分号分隔的键值对列表,document.cookie = "aKey=5"即将设置/更新aKeycookie。

So yes, document.cookieshows special behavior.

所以是的,document.cookie表现出特殊的行为。

回答by Sascha Galley

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.

您可以通过简单地将其过期时间更新为零来删除 cookie。