[英]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.