英文:
Store an array in a cookie
问题
我想将一个数组存储在cookie中,以便以后使用。我不知道为什么,但输出不是一个数组。我尝试将其字符串化并解析,但结果没有改变。
var arr = '["Template 43","normal"]';
console.log(arr) // => ["Template 43","normal"]
value = JSON.stringify(arr)
console.log(value) // => "["Template 43","normal"]"
setCookie_text('meta_template', value)
cookie = getCookie('meta_template')
h = JSON.parse(cookie);
console.log(h) // => ["Template 43","normal"]
console.log(h[0]) // => [
英文:
I want to store an array in a cookie in order to get it later. I don't know why but the output is not an array. I tried to stringify it and parse it but it doesn't change anything.
var arr = '["Template 43","normal"]'
console.log(arr) // => ["Template 43","normal"]
value = JSON.stringify(arr)
console.log(value) // => "[\"Template 43\",\"normal\"]"
setCookie_text('meta_template', value)
cookie = getCookie('meta_template')
h = JSON.parse(cookie);
console.log(h) // => ["Template 43","normal"]
console.log(h[0]) // => [
答案1
得分: 2
你将arr
定义为string
,而不是array
!
尝试这样做,应该可以工作:
var arr = ["Template 43", "normal"];
console.log(arr);
var value = JSON.stringify(arr);
console.log(value);
setCookie_text('meta_template', value);
var cookie = getCookie('meta_template');
var h = JSON.parse(cookie);
console.log(h);
console.log(h[0]);
英文:
You are defining arr
as a string
, not array
!
Try this, this should work:
var arr = ["Template 43", "normal"];
console.log(arr);
var value = JSON.stringify(arr);
console.log(value);
setCookie_text('meta_template', value);
var cookie = getCookie('meta_template');
var h = JSON.parse(cookie);
console.log(h);
console.log(h[0]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论