[英]How to add/append JavaScript sourced data into an existing DataTables Table?
[英]How to add/append to existing Web storage in javascript?
我正在嘗試使用此代碼添加/添加到新的/現有的localStorage:
function add(){
var name = document.getElementById("name").value;
var ort = document.getElementById("ort").value;
var user = {"name":name, "ort":ort};
var exist = [];
var tmp = (JSON.parse(localStorage.getItem("users")));
if(tmp)
exist.push(tmp);
exist.push(user);
localStorage.setItem("users",JSON.stringify(exist));
console.log(JSON.parse(localStorage.getItem("users")));
var obj = JSON.parse(localStorage.getItem("users"));
for(var i=0; i<obj.length; i++) {
console.log('key: ' + i + '\n' + 'value: ' + obj[i]);
}
}
研究Chrome開發者工具的localStorage看起來像這樣:
[[{"name":"a","city":"a"}],{"name":"b","city":"b"}]
但是我想要的是:
[{"name":"a","city":"a"},{"name":"b","city":"b"}]
我究竟做錯了什么?
任何幫助表示贊賞,
最好的祝福,
localStorage
僅存儲strings
。 您需要stringify
你的exist
,然后將其保存到storage
localStorage.setItem("users",JSON.stringify(exist));
要檢索它,請使用JSON.parse
var exist = JSON.parse(localStorage.exist); //Even for users object do the same
更新
要只將tmp
數組中的對象exist
使用map()
:
tmp.map(function(item){
exist.push(item);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.