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

store array into localstorage instead of replace

本文关键字:存储 替换 数组      更新时间:2023-09-26

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

  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);

下面是一个完整的功能示例(实时复制;遗憾的是,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;");
  }
})();

补充说明:如果您有可能在某个时候不得不在没有本地存储的旧浏览器上支持您的代码,那么如果您使用更详细的.getItem(...)/.setItem(..., ...) API,您可以选择使用写入cookie的polyfill,因为它们可以是多填充的,而通过[]访问则不能。

localStorage支持字符串。您应该使用JSON的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对象。

如本文所述您还可以通过以下方式扩展默认存储对象以处理阵列和对象:

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