Reputation: 155
i have made a small sumon math game where i have created 9 listitems with diffrent numbers on each listitem and every time value changes as the pages reload(random values come evreytime).
User has to click on the listitems to achieve the goal e.g suppose achieving target is 7 so user will click on 5 and 2 or watever to achieve 7.
Now what i want to do is suppose when i achieved the goal i want to save it in my local storage and next time when user restarts it and achieves a new values that too i want to store in local storage so what my point is to store data in an array format inside localstorage every time user achieves the goal.
Here is data_stack array which adds up the value and stores it into current value so i want to push this currentval everytime to an array.Please help me here
var currentval = eval(data_stack.join('+'));
console.log(currentval);
Upvotes: 0
Views: 371
Reputation: 64536
The key/value local storage (aka Web Storage) only accepts strings. However, you can JSON encode your array and store the JSON, so when you retrieve it just decode it back to an array.
Storing the array as JSON:
// data_stack is an array
// store as JSON
localStorage.setItem('data_stack', JSON.stringify(data_stack));
Retrieving the JSON and decoding it:
var raw = localStorage.getItem('data_stack');
if(raw !== null) {
var data_stack = JSON.parse(raw);
// now you can push to data_stack or whatever
data_stack.push('xyz');
}
Upvotes: 1