【问题标题】:Pushing input value to array in local storage goes wrong将输入值推送到本地存储中的数组出错
【发布时间】:2023-03-03 00:50:01
【问题描述】:

对于我正在处理的项目,我想将输入字段中的值存储在存储在本地存储中的数组中。通过在这里查找较旧的问题,我已经设法取得了很长的路要走,但仍然有些事情不对劲。当我在输入某些内容后使用 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() 的按钮。

我做错了什么?

【问题讨论】:

    标签: javascript arrays json local-storage


    【解决方案1】:

    你可以试试这个代码:

    // 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(使用开发者工具查看本地存储内容)。

    【讨论】:

    • 像魅力一样工作,谢谢!你的解释让我意识到我做错了什么。
    【解决方案2】:

    问题是您将数组names 放入了从本地存储中获取的数组。

    改变

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

    var names = []; // always declare your variables
    if (localStorage.getItem('locname')) {
        names = JSON.parse(localStorage.getItem('locname'));
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-13
      • 1970-01-01
      • 2021-12-22
      • 2015-09-29
      • 2016-01-05
      • 2022-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多