javascript - 将输入值推送到本地存储中的数组出错

标签 javascript arrays json local-storage

对于我正在从事的项目,我想将输入字段中的值存储在存储在本地存储中的数组中。通过在这里查找较旧的问题,我已经取得了很大的进展,但仍然有些事情不太顺利。当我使用 console.log 检查输入内容后数组是否已填充时,它在我的控制台中显示一堆嵌套数组,我不知道如何修复/使用它们。

我的js:

names = [];
names.push(JSON.parse(localStorage.getItem('locname')));
localStorage.setItem('locname', JSON.stringify(names));

function saveData(data) {

  names = [];
  var data = document.getElementById("locationName").value;
  names = JSON.parse(localStorage.getItem('locname'));
  names.push(data);
  alert(names);
  localStorage.setItem('locname', JSON.stringify(names));
}

console.log(names);

在我的 HTML 中,我有一个 id=locationName 的输入和一个 onclick=saveData() 的按钮。

我做错了什么?

最佳答案

您可以尝试以下代码:

// Read value from storage, or empty array.
// You were doing something different here - you were putting array
// from localStorage into your "names" array, so for every page refresh
// you would make this structure deeper by 1.
var names = JSON.parse(localStorage.getItem('locname') || "[]");

function saveData(data) {
  var data = document.getElementById("locationName").value;
  names.push(data);
  localStorage.setItem('locname', JSON.stringify(names));
}

Working example on JSFiddle (使用开发者工具查看本地存储内容)。

关于javascript - 将输入值推送到本地存储中的数组出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24045623/

相关文章:

我网页的 Javascript 部分无法正常工作

javascript - 为什么数组的旧内容被删除了?

javascript - 在 react-router-dom 中将 id 作为 props 传递

arrays - 将数组尽可能均匀地划分为子数组以进行核心映射

arrays - 如何获取哈希数组中元素的数量?

javascript - 数组结构中字符串的 JSON.parse 语法问题

c# - 中继 JSON 已转义双引号

java - 如何将 Jmol 小程序放入网页中?

javascript - 使用 JSON 数组填充输入字段

android - bufferedReader() 在 Kotlin 中究竟是如何工作的?