document.cookie 到底是如何工作的?
如果我通过进入控制台并输入 document.cookie;
让 Chrome 向我显示 document.cookie
,它会给我说:
"name=John 到
但是,如果我输入 document.cookie = 5;
,它所做的只是将 5;
添加 字符串,所以我得到:
"5; name=John; sex=male";
如果我尝试 document.cookie = null;
那么它甚至不会做任何事情。
怎么会这样呢?这是一个变量,不是吗?那么为什么赋值运算符没有按应有的方式工作呢?它实际上只是一点语法糖而不是真正的变量吗?如果是这样,糖到底掩盖了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
document.cookie
有非常特殊的行为。正如您所见,分配给它会添加(或更新)一个 cookie(或多个 cookie),而不是替换所有 cookie。这很不寻常。在 MDN 上阅读所有相关内容。
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.
为什么不看看 MDN?
赋值运算符右侧的字符串
document.cookies
应该是以分号分隔的键值对列表,即document.cookie = "aKey=5"
将设置/更新aKey< /代码> cookie。
所以,是的,
document.cookie
显示了特殊的行为。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 theaKey
cookie.So yes,
document.cookie
shows special behavior.以下是您的“问题”的示例。此外,它还说了以下内容:
Here is an example of your "issue". Also, it says the following: