【问题标题】:Want to push data to an array, but the new data replaces the old data想推数据到数组,但是新数据替换了旧数据
【发布时间】:2020-10-09 09:50:15
【问题描述】:

当我想将数据推送到localStorage 数组时,新数据替换旧数据。我该如何解决?

function addNametext(e) {

    const arrData = inpot1.value

    let text1;
    if (localStorage.getItem("text1") === null) {

        text1 = [];

    } else {

        text1 = JSON.parse(localStorage.getItem("text1"));

    }
    text1.push(arrData);

    localStorage.setItem("name", JSON.stringify(text1));

    alert("SAVED");

    e.preventDefault();
}

【问题讨论】:

  • LocalStorage 存储键/值对。每个键可以保存一个字符串值,所以如果你不断地覆盖同一个键,你也会不断地覆盖这个值。
  • 感谢您的回答,但我需要制作一个保存数组值的键

标签: javascript arrays javascript-objects dom-events


【解决方案1】:

您正在使用名称 name 设置密钥,但使用 text1 获取。你需要纠正它

text1 = JSON.parse(localStorage.getItem("text1")); //Notice the key

localStorage.setItem("name", JSON.stringify(text1)); //Notice the key here

【讨论】:

猜你喜欢
  • 2019-02-24
  • 2011-11-06
  • 2019-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多