简体   繁体   English

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

[英]store array into localstorage instead of replace

I'm using local storage as below like 我正在使用本地存储,如下所示

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

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

I want to create nested json in my localstorage, if above code is within a click event for the user to click save, it will delete the old data and replace it. 我想在本地存储中创建嵌套的json,如果上述代码位于click事件中,供用户单击“保存”,它将删除旧数据并替换它。 How to push new value as an array object? 如何将新值作为数组对象推送?

Use an actual array, eg on page load: 使用实际的数组,例如在页面加载时:

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

Then as you're working with it, add to the array in memory: 然后,在使用它时,将其添加到内存中的数组中:

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

Any time you want to save the value back to local storage: 任何时候要将值保存回本地存储:

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

Here's a complete functional example ( live copy ; sadly, Stack Snippets disallow local storage): 这是一个完整的功能示例( 实时复制 ;可悲的是,堆栈片段禁止本地存储):

HTML: 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 (must be after the HTML in the document): 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;");
  }
})();

Side note: If there's any chance at all you might have to support your code on older browsers that don't have local storage at some point, you can give yourself the option of using a polyfill that writes to cookies if you use the more verbose .getItem(...) / .setItem(..., ...) API, as they can be polyfilled whereas accessing via [] as in the above can't be. 旁注:如果您完全有可能在某个时候没有本地存储的旧版浏览器上支持代码,则可以选择使用写成cookie的polyfill(如果您使用更详细的代码) .getItem(...) / .setItem(..., ...) API,因为它们可以被填充,而不能像上面那样通过[]访问。

localStorage supports strings. localStorage支持字符串。 You should use JSONs stringify() and parse() methods. 您应该使用JSONs stringify()和parse()方法。

If I understood the question and what you are looking for is storing an array and not just an object with properties. 如果我理解这个问题,并且您正在寻找的是存储数组,而不仅仅是存储具有属性的对象。

As scunliffe commented, What you can do in order to add items to an array which is stored in the local storage is: Generating the array with first object: 正如scunliffe所评论的,为了将项目添加到存储在本地存储中的数组中,您可以执行以下操作:使用第一个对象生成数组:

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

Adding items to the array: 向数组添加项目:

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

This way you store an JSON object representing an array. 这样,您可以存储代表数组的JSON对象。

As mentioned in this post You can also extend the default storage-objects to handle arrays and objects by: 正如提到的这篇文章 ,您还可以扩展默认的存储对象的处理数组和对象:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM