[英]store array into localstorage instead of replace
我正在使用本地存储,如下所示
var post = {
title: 'abc',
price: 'USD5'
};
window.localStorage['book'] = JSON.stringify(post);
我想在本地存储中创建嵌套的json,如果上述代码位于click事件中,供用户单击“保存”,它将删除旧数据并替换它。 如何将新值作为数组对象推送?
使用实际的数组,例如在页面加载时:
var posts = JSON.parse(localStorage['book'] || "[]");
然后,在使用它时,将其添加到内存中的数组中:
posts.push({
title: 'abc',
price: 'USD5'
});
任何时候要将值保存回本地存储:
localStorage['book'] = JSON.stringify(posts);
这是一个完整的功能示例( 实时复制 ;可悲的是,堆栈片段禁止本地存储):
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, "&").replace(/</g, "<");
}
})();
旁注:如果您完全有可能在某个时候没有本地存储的旧版浏览器上支持代码,则可以选择使用写成cookie的polyfill(如果您使用更详细的代码) .getItem(...)
/ .setItem(..., ...)
API,因为它们可以被填充,而不能像上面那样通过[]
访问。
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对象。
正如提到的这篇文章 ,您还可以扩展默认的存储对象的处理数组和对象:
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.