You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cookie中存储数组?解析后无法正常访问数组元素

问题分析与解决

你的核心问题是初始变量arr根本不是数组,而是一个JSON格式的字符串,后续操作对字符串做了重复序列化,导致最终解析后还是字符串,而非数组。

错误原因拆解

  • 你定义的var arr = '["Template 43","normal"]'是字符串类型,不是数组。
  • 对这个字符串执行JSON.stringify(arr),会把它转成带转义符的字符串(比如"[\"Template 43\",\"normal\"]")。
  • 存入cookie再取出解析后,得到的还是最初的JSON字符串,所以h是字符串,h[0]自然取到字符串的第一个字符[。

修正后的代码

// 1. 先把初始的JSON字符串解析成真正的数组
var arr = JSON.parse('["Template 43","normal"]');
console.log(arr); // => ["Template 43", "normal"](这才是数组)

// 2. 对数组执行JSON.stringify,转成可存储的字符串
var value = JSON.stringify(arr);
console.log(value); // => "[\"Template 43\",\"normal\"]"

// 3. 存入cookie
setCookie_text('meta_template', value);

// 4. 取出并解析
var cookie = getCookie('meta_template');
var h = JSON.parse(cookie);
console.log(h); // => ["Template 43", "normal"](数组)
console.log(h[0]); // => "Template 43"(正确取到数组第一个元素)

关键要点

  • 存储数组到cookie的正确流程:数组 → JSON.stringify转字符串 → 存cookie
  • 读取时:取cookie字符串 → JSON.parse转数组
  • 如果初始数据是JSON格式的字符串,第一步必须先解析成数组,再进行后续操作。

内容的提问来源于stack exchange,提问作者Mathieu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 10:27:54