如何在 JavaScript cookie 中存储数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3408463/
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-10-25 01:05:28  来源:igfitidea点击:

How to store an array in a JavaScript cookie?

javascriptarrayscookies

提问by Josh

Does anyone have a piece of JavaScript code that creates a cookie and stores an array in it? If you also have the code to read through through cookie and delete it, that would be great as well. Thanks!

有没有人有一段 JavaScript 代码来创建一个 cookie 并在其中存储一个数组?如果您还有通过 cookie 读取并删除它的代码,那也很棒。谢谢!

采纳答案by Christian Smorra

have a look at: http://plugins.jquery.com/project/cookiehttps://plugins.jquery.com/cookie/

看一下: http://plugins.jquery.com/project/cookiehttps://plugins.jquery.com/cookie/

to store an array

存储数组

$.cookie('COOKIE_NAME', escape(myarray.join(',')), {expires:1234});

to get it back

把它拿回来

cookie=unescape($.cookie('COOKIE_NAME'))
myarray=cookie.split(',')

回答by fzzle

jQuery, Cookie plugin:
Converting an array into a string:

jQuery、Cookie 插件
将数组转换为字符串:

> JSON.stringify([1, 2]);
> '[1, 2]'

Then:

然后:

$.cookie('cookie', '[1, 2]');

And then parse it:

然后解析它:

JSON.parse($.cookie('cookie'));
> [1, 2]