存储阵列到localStorage的,而不是取代阵列、而不是、localStorage

2023-09-13 04:17:41 作者:Ombre amant 影子爱人

我使用本地存储如下像

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

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

我想在我的localStorage来创建嵌套JSON,如果高于code是用户点击事件中点击保存,将删除旧数据并更换。如何推动新的值作为数组对象?

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. How to push new value as an array object?

推荐答案

localStorage的支持字符串。你应该字符串化(使用JSONs)和解析()方法。

localStorage supports strings. You should use JSONs stringify() and parse() methods.

如果我的理解这个问题,你正在寻找的是存储阵列,而不只是一个对象的属性。

If I understood the question and what you are looking for is storing an array and not just an object with properties.

由于scunliffe评论,你可以为项目添加到存储在本地存储阵列做的是:生成与第一个对象数组:

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:

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

这样,你存储一个JSON对象重新presenting数组。

This way you store an JSON object representing an array.

如这个帖子您还可以扩展默认的存储对象来处理由数组和对象:

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