document.cookie究竟如何工作? [英] How exactly does document.cookie work?

查看:146
本文介绍了document.cookie究竟如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我让Chrome通过进入控制台并输入 document.cookie; 来显示我 document.cookie 说:

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;

但是,如果我输入,说, document.cookie = 5; 所有它是添加 5; 到字符串的开始,所以我得到:

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 =男性;

如果我尝试 document.cookie = null; 那么它不甚至不做任何事情。

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?

推荐答案

document.cookie 具有非常特殊行为。如你所见,分配给它添加了一个cookie(或更新)一个cookie(或多个cookie),而不是替换所有的cookie。这是非常不寻常的。

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.

阅读全文:

  • MDN
  • MSDN

这篇关于document.cookie究竟如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆