在cookie中存储一个数组

huangapple go评论64阅读模式
英文:

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]);

huangapple
  • 本文由 发表于 2023年4月19日 17:14:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76052745.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定