Hay*_*n E 2 javascript arrays cookies
我使用以下方法在 cookie 中存储和检索值:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
};
Run Code Online (Sandbox Code Playgroud)
和
function getCookie() {
var name = "name=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
};
Run Code Online (Sandbox Code Playgroud)
现在我需要以类似的方式存储/检索数组。我知道我需要将数组创建为单个字符串,然后将其解析回来,但是最好的方法是什么?
我建议使用JSON。首先,将数组转换为 JSON 字符串:
var array = ["one","two","three"];
var json_string = JSON.stringify(array);
Run Code Online (Sandbox Code Playgroud)
然后使用 JSON 字符串作为值设置 cookie。
setCookie("array", json_string, exdays);
Run Code Online (Sandbox Code Playgroud)
然后,当您稍后从 cookie 中检索 JSON 字符串时,将其转换回实际的数组。
var json_string = getCookie("array");
var array = JSON.parse(json_string);
Run Code Online (Sandbox Code Playgroud)