Javascript 如何将多个类似类型的对象添加到本地存储

Javascript 如何将多个类似类型的对象添加到本地存储,javascript,local-storage,Javascript,Local Storage,我在这里和其他一些站点上看到了几种将对象添加到本地存储的解决方案,但我的问题略有不同。我想将几个相关项目保存到本地存储。 像这样的 <head> <script type="text/javascript" src="jquery.js"></script> </head> <body> <input type='text' id='firstname' placeholder="first name"><br>

我在这里和其他一些站点上看到了几种将对象添加到本地存储的解决方案,但我的问题略有不同。我想将几个相关项目保存到本地存储。 像这样的

<head>
<script type="text/javascript" src="jquery.js"></script>

</head>
<body>
<input type='text' id='firstname' placeholder="first name"><br>
<input type='text' id='surname' placeholder="surname"><br>
<button id='submit'>Add</button>

<div id='displaynames'>

 <script>
$(document).ready(function(){
    $('button').click(function(){

        firstname = $('#firstname').val();
        surname = $('#surname').val();
        $('#displaynames').append("<p>"+firstname+" "+surname+"</p>");

        var names = {
            id: //what goes here?,
            name: firstname,
            lastname: surname
        };

        localStorage.setItem('names:'+counter, JSON.stringify(names));
        counter++;
        $('#displaynames').html(localStorage.getItem('names'));

    });
})   
</script>
</body>



添加 $(文档).ready(函数(){ $(“按钮”)。单击(函数(){ firstname=$('#firstname').val(); 姓氏=$(“#姓氏”).val(); $('#displaynames')。追加(“”+名字+”+姓氏+”

”); 变量名称={ id://这里有什么?, 姓名:名字, 姓氏 }; setItem('names:'+counter,JSON.stringify(names)); 计数器++; $('#displaynames').html(localStorage.getItem('names')); }); })
此对象的所有属性都将由用户提供,但没有两个对象具有相同的id来区分它们,更重要的是,没有两个对象可以具有相同的密钥名,如何实现这一点?我的代码中有某种循环


我希望该键可以像names:1、names:2、names:3等那样递增。您还可以将
计数器本身存储在本地存储器中,因此每次需要添加新项时,都要确保递增计数器

// Get current counter from LS and increment it
var counter = localStorage.getItem('counter');
counter++;

// Put names in LS with a new counter id
localStorage.setItem('names:'+counter, JSON.stringify(names));

// Put back the incremented counter into LS
localStorage.setItem('counter', counter);

但正如一篇评论中所建议的那样,使用一个数组将你所有的
名字都放在上面会更明智。添加新名称时,其
id
可以是
名称:“+namesArray.length
尝试使用数组,您可以在数组中存储对象,我的示例:

$(文档).ready(函数(){
var allNames=[];
$(“按钮”)。单击(函数(){
firstname=$('#firstname').val();
姓氏=$(“#姓氏”).val();
$('#displaynames')。追加(“”+名字+”+姓氏+”

”); 变量名称={ id:allNames.length, 姓名:名字, 姓氏 }; allNames.push(名称); localStorage.setItem('names',JSON.stringify(allNames)); $('#displaynames').html(localStorage.getItem('names')); }); });



添加
通过对相似类型对象ID的串联引用来存储相似类型对象的代码:

    let productBag = window.localStorage.getItem("product_id");

    console.log(productBag);

    if (productBag != undefined) {

      let tempData = productBag + "," + product['_id'];
      window.localStorage.setItem("product_id", tempData);

    } else {

      window.localStorage.setItem("product_id", product['_id']);

    }
按项目ID显示项目的代码:

 var test =  window.localStorage.getItem("product_id")

 console.log(test.split(","));

您需要
id
做什么?为什么不直接使用
计数器