存储阵列到localStorage的,而不是取代 [英] store array into localstorage instead of replace

查看:199
本文介绍了存储阵列到localStorage的,而不是取代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用本地存储如下像

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

这篇关于存储阵列到localStorage的,而不是取代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆