不能将数据放在localstorage中多次

时间:2018-03-07 06:14:07

标签: javascript jquery local-storage

var bookobj = {
    Name: name,
    Author: author,
    Edition: edi,
    Price: pri
}

var arr = [];
if(localStorage === null){
    localStorage.setItem("Arrayobj", JSON.stringify(bookobj));
} else {
    arr.push(bookobj);
    localStorage.setItem("Array", JSON.stringify(arr));   
}

我已经创建了一个对象并将其推送到数组。但是每次都会在localStorage中覆盖细节。

1 个答案:

答案 0 :(得分:3)

尝试此操作,添加注释以解释其工作原理。

var bookobj = {
  Name: name,
  Author: author,
  Edition: edi,
  Price: pri,
}

// read what the 'books' value currently is
// the `|| '[]'` makes it so that, if it's null, it defaults to a string of an empty array
// which, when passed to JSON.parse, turns into an empty array
var books = JSON.parse(localStorage.getItem('books') || '[]')

// add the book object to the temporary books variable
books.push(bookobj)

// re-save it back to local storage
localStorage.setItem('books', JSON.stringify(books))

您当前的代码无效,因为:

  1. if (localStorage === null)行并未实际检查本地存储中的变量。为此,您需要执行if (localStorage.getItem('...') === null)。但是,我选择在我的解决方案中使用||来保持清洁。

  2. 每次创建数组并保存它将不断覆盖存储中的数组,而不是读取并添加到存储中的数据。

  3. if语句的第一部分中,数组实际上并未保存到存储中,只有bookobj本身。