本地会话中的动态数组

时间:2017-10-28 00:19:21

标签: javascript html arrays html5 local-storage

我遇到使用本地会话变量的逻辑问题。所以我理解HTML5允许您设置和获取这些本地存储变量。

我已阅读此帖:adding objects to array in localStorage 并且理解通过使用SetItem,您将重写已设置的变量,因此对于动态数组,您需要在推送新值之前先获取变量。

所以我遇到的问题,我甚至不知道它是否可能,是我想拥有一个例如一个接受用户输入的index.html页面并将其添加到需要持久化的数组中。当用户重新加载同一页面时,先前的输入仍将在同一个数组中。从我之前提到的帖子中读到的内容,如果你使用SetItem,你将重写变量。但是,如果我不使用setItem,我怎么能指定该数组是一个本地存储变量......如果我困惑任何人,我很抱歉...因为我很困惑我。提前谢谢。

2 个答案:

答案 0 :(得分:0)

您的所有假设都是正确的。您只能使用setItem写入localStorage,并且在调用setItem时,您将覆盖其中存在的任何值。因此,将项添加到localStorage中的数组的唯一方法是从localStorage获取数组,对其进行操作,然后将其与新项一起放回。

// Check if we already have an array in local storage.
var x = localStorage.getItem("myArray");
// If not, create the array.
if (x === null) x = [];
// If so, decode the array. 
else x = JSON.parse(x);
// Add our new item. 
x.push("value 1");
// Encode the array.
x = JSON.stringify(x);
// Add back to LocalStorage. 
localStorage.setItem("myArray", x);

答案 1 :(得分:0)

这可以通过以下方法完成:

var myInput = document.getElementById("myInput").value; // user data
var myList = JSON.parse(localStorage.getItem("myList")); // retrieve the list from LS
if(!Array.isArray(myList)) { // if LS list is not ok, instantiate new array
  myList = [];
}
myList.push(myInput); // append user data to the list
localStorage.setItem("myList", JSON.stringify(myList)); // save the list back to LS