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

如何将输入值正确推入localStorage存储的数组中?

核心问题

两次写法的错误原因一致:你从localStorage解析得到的结果本身就是数组结构,额外对其套了一层数组包装,最终产生了嵌套的二维数组结构。

修复方案

读取本地存储数据时做好空值兼容(避免首次存储时解析结果为null报错),直接对原数组做追加操作即可,不要额外套数组。

写法1:直接push修改原数组

// 读取存储值,首次存储无数据时默认赋值为空数组
const arr = JSON.parse(localStorage.getItem("Table")) ?? [];
// 追加新值
arr.push(document.getElementById("select").value);
// 序列化后存回
localStorage.setItem("Table", JSON.stringify(arr));

如果需要兼容ES2020以下的运行环境,可以把空值合并运算符??替换为逻辑或运算符||。

写法2:扩展运算符合并生成新数组

const arr = JSON.parse(localStorage.getItem("Table")) ?? [];
const newArr = [...arr, document.getElementById("select").value];
localStorage.setItem("Table", JSON.stringify(newArr));

运行上述代码后存储的结构就是你期望的["", "Data1", "Data2"]格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:36:03