Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

javascript - How exactly does document.cookie work?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...