将数组存储到本地存储而不是替换

store array into localstorage instead of replace

我正在使用本地存储,如下所示

  var post = {
    title: 'abc',
    price: 'USD5'
  };

window.localStorage['book'] = JSON.stringify(post);

我想在我的本地存储中创建嵌套 json,如果上面的代码在用户点击保存的点击事件中,它将删除旧数据并替换它。如何将新值推送为数组对象?

使用实际数组,例如页面加载:

var posts = JSON.parse(localStorage['book'] || "[]");

然后在使用它时,将其添加到内存中的数组中:

posts.push({
   title: 'abc',
   price: 'USD5'
});

任何时候你想将值保存回本地存储:

localStorage['book'] = JSON.stringify(posts);

这是一个完整的功能示例(live copy;遗憾的是,Stack Snippets 不允许本地存储):

HTML:

<div>
  <label>
    Name:
    <input type="text" id="txt-name">
  </label>
</div>
<div>
  <label>
    Price:
    <input type="text" id="txt-price">
  </label>
</div>
<div>
  <input type="button" value="Add" id="btn-add">
</div>
<div id="list"></div>

JavaScript(必须在文档中的HTML之后):

(function() {
  var nameField = document.getElementById("txt-name"),
    priceField = document.getElementById("txt-price");

  // On page load, get the current set or a blank array
  var list = JSON.parse(localStorage.getItem("list") || "[]");

  // Show the entries
  list.forEach(showItem);

  // "Add" button handler
  document.getElementById("btn-add").addEventListener(
    "click",
    function() {
      // Get the name and price
      var item = {
        name: nameField.value,
        price: priceField.value
      };

      // Add to the list
      list.push(item);

      // Display it
      showItem(item);

      // Update local storage
      localStorage.setItem("list", JSON.stringify(list));
    },
    false
  );

  // Function for showing an item
  function showItem(item) {
    var div = document.createElement('div');
    div.innerHTML =
      "Name: " + escapeHTML(item.name) +
      ", price: " + escapeHTML(item.price);
    document.getElementById("list").appendChild(div);
  }

  // Function for escaping HTML in the string
  function escapeHTML(str) {
    return str.replace(/&/g, "&amp;").replace(/</g, "&lt;");
  }
})();

旁注:如果有任何机会您可能不得不在某些时候没有本地存储的旧浏览器上支持您的代码,您可以选择使用写入 cookie 的 polyfill,如果您使用更详细的 .getItem(...)/.setItem(..., ...) API,因为它们可以被 polyfilled 而通过 [] 访问不能像上面那样。

localStorage 支持字符串。您应该使用 JSONs stringify() 和 parse() 方法。

如果我理解这个问题并且您要查找的是存储数组而不仅仅是具有属性的对象。

正如 scunliffe 评论的那样,为了将项目添加到存储在本地存储中的数组,您可以做的是: 用第一个对象生成数组:

var array = []; 
array[0] = //Whatever; 
localStorage["array"] = JSON.stringify(array);

向数组添加项目:

//Adding new object 
var storedArray = JSON.parse(localStorage["array"]);
sotreadArray.push(//Whatever); 
localStorage["array"] = JSON.stringify(array);

通过这种方式,您可以存储一个 JSON 表示数组的对象。

this post所述 您还可以通过以下方式扩展默认存储对象以处理数组和对象:

Storage.prototype.setObj = function(key, obj) {
    return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
    return JSON.parse(this.getItem(key))
}