如何在javascript中添加/追加到现有的Web存储

How to add/append to existing Web storage in javascript?

本文关键字:存储 Web 追加 javascript 添加      更新时间:2023-09-26

我正在尝试使用此代码添加/追加到新的/现有的localStorage:

 function add(){
    var name = document.getElementById("name").value;
    var ort = document.getElementById("ort").value;
    var user = {"name":name, "ort":ort};
    var exist = [];
    var tmp = (JSON.parse(localStorage.getItem("users")));
    if(tmp)
        exist.push(tmp);
    exist.push(user);
    localStorage.setItem("users",JSON.stringify(exist));
    console.log(JSON.parse(localStorage.getItem("users")));
    var obj = JSON.parse(localStorage.getItem("users"));
    for(var i=0; i<obj.length; i++) {
        console.log('key: ' + i + ''n' + 'value: ' + obj[i]);
    }

}

查看Chrome开发工具localStorage看起来像这样:

   [[{"name":"a","city":"a"}],{"name":"b","city":"b"}]

但是我想要的是:

   [{"name":"a","city":"a"},{"name":"b","city":"b"}]

我做错了什么?

感谢任何帮助,

问好,

localStorage只存储strings。你需要stringify你的exist,然后保存到storage

localStorage.setItem("users",JSON.stringify(exist));

使用JSON.parse

var exist = JSON.parse(localStorage.exist); //Even for users object do the same

只将数组tmp中的对象推入exist,使用map():

tmp.map(function(item){
 exist.push(item);
})