如何在数组中存储本地存储的值,JavaScript?

时间:2022-06-24 17:29:35

I have been trying to code in javascript where I want input given to be displayed on screen. I want to store the data from input in LocalStorage. I tried to take the value and using localStorage.setItem and localStorage.getItem I stored in local storage too. But as I want to display all the records I have inserted every time submit button has been clicked, I want to store current and previous records too. I tried to push into an array but it had only current records and not previously stored values. I don't want jquery. I just want simple javascript code. thank you.

我一直在尝试在javascript中编码,我希望输入给出显示在屏幕上。我想将输入数据存储在LocalStorage中。我试图获取值并使用localStorage.setItem和localStorage.getItem我也存储在本地存储中。但是,由于我想显示每次单击提交按钮时插入的所有记录,我也想存储当前和以前的记录。我试图推入一个数组,但它只有当前记录,而不是以前存储的值。我不想要jquery。我只想要简单的JavaScript代码。谢谢。

   eg-
    var data=[];
    function myFunction(data)
    { 
         var name= document.getElementById("nm").value;
         localStorage.name= name;
         for(var i=0;i<localStorage.length;i++)
         {
             var key = localStorage.key(i);
             var value = localStorage.getItem(key);
             data.push( value);
         }
     }

1 个解决方案

#1


2  

Yep, as mentioned in the comments it is best to just store the String representation of your array and store it as a value in localstorage. Web localstorage lets you store simple key value pairs which can be integers or strings (mostly strings) official docs

是的,正如评论中所提到的,最好只存储数组的String表示形式,并将其存储为localstorage中的值。 Web localstorage允许您存储简单的键值对,可以是整数或字符串(主要是字符串)官方文档

You could do something like this:

你可以这样做:

 var name= document.getElementById("nm").value;
 var data;
 if (localStorage.getItem("name") === null)
   //First value to be stored
   data = [];
 else
   //There is some value already in the array
   data = JSON.parse(localStorage.getItem("name"));

 //Push name to data array in any case
 data.push(name);
 //Update localStorage
 localStorage.setItem("name",JSON.stringify(data));

I hope this gets you started in the right direction.

我希望这能让你开始朝着正确的方向前进。

#1


2  

Yep, as mentioned in the comments it is best to just store the String representation of your array and store it as a value in localstorage. Web localstorage lets you store simple key value pairs which can be integers or strings (mostly strings) official docs

是的,正如评论中所提到的,最好只存储数组的String表示形式,并将其存储为localstorage中的值。 Web localstorage允许您存储简单的键值对,可以是整数或字符串(主要是字符串)官方文档

You could do something like this:

你可以这样做:

 var name= document.getElementById("nm").value;
 var data;
 if (localStorage.getItem("name") === null)
   //First value to be stored
   data = [];
 else
   //There is some value already in the array
   data = JSON.parse(localStorage.getItem("name"));

 //Push name to data array in any case
 data.push(name);
 //Update localStorage
 localStorage.setItem("name",JSON.stringify(data));

I hope this gets you started in the right direction.

我希望这能让你开始朝着正确的方向前进。