dynamic array to local storage/jstorage?

你离开我真会死。 提交于 2019-12-08 08:41:16

问题


I am pushing values in to my array every 10 seconds which is being displayed by innerHTML on a div.

Onreload or on visit to some other web page I want to display the already pushed content and the content being pushed presently. I have gone through local stroage and jstorage tutorials.

This is what I am doing precisely=:

localStorage.setItem('names', xyz);

I know how to store one variable,but what when we have a dynamic array being updated/10sec and data being pushed in it every 10 seconds.how do I set and get this dynamic array even when I go to some other link.

If you are interested in my code:http://jsfiddle.net/vCcnB/

UPDATE 1----for simplification(ignore if you have understood.) This is what is being displayed in my div.Page1 indicates the page and 0,10,20 indicates time.

@ 10 seconds----[page1,0]
                [page1,10]

@20 seconds-----[page1,0]
                [page1,10]
                [page1,20]
    now a click to some other page.

@10 seconds----[page1,0]
               [page1,10]
               [page1,20]
               [page2,0]
               [page2,10]
    now a click to some other page.

@20 seconds----[page1,10]
               [page1,20]
               [page2,0]
               [page2,10]
               [page3,0]
               [page3,10]
               [page3,20]    

回答1:


You can use json object for this like,

localStorage.setItem('names', {'ABC','XYZ'}); //and so on

or json string like

var json={'ABC','XYZ'};
localStorage.setItem('names', JSON.stringify(json)); //and so on

To get an existing item try this,

console.log(localStorage.getItem('names'));

Read this https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Storage




回答2:


You have to JSON.stringify and JSON.parse your array to store and load it respectively.

// initialize
var myArray = [];
// load saved array
if(window.localStorage["savedArray"] != null)
    myArray = JSON.parse(window.localStorage["savedArray"]);
// modify array
myArray.push("abc123");
// re-save array
window.localStorage["savedArray"] = JSON.stringify(myArray);


来源:https://stackoverflow.com/questions/17654312/dynamic-array-to-local-storage-jstorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!