简体   繁体   English

需要将数据存储在本地存储中的数组中?

[英]need to store the data in an array inside localstorage?

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). 我做了一个小型的Sumon数学游戏,在其中我创建了9个列表项,每个列表项上都有不同的数字,并且每次页面重新加载时值都会改变(随机值到evreytime)。

User has to click on the listitems to achieve the goal eg suppose achieving target is 7 so user will click on 5 and 2 or watever to achieve 7. 用户必须单击列表项以实现目标,例如,假设达到目标为7,则用户将单击5和2或watever来实现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 这是data_stack数组,它将值加起来并存储为当前值,所以我想每次将此currentval推送到数组。请在这里帮助我

var currentval =  eval(data_stack.join('+'));
console.log(currentval);

The key/value local storage (aka Web Storage ) only accepts strings. 键/值本地存储(又名Web存储 )仅接受字符串。 However, you can JSON encode your array and store the JSON, so when you retrieve it just decode it back to an array. 但是,您可以对数组进行JSON编码并存储JSON,因此在检索它时,只需将其解码回数组即可。

Storing the array as JSON: 将数组存储为JSON:

// data_stack is an array
// store as JSON
localStorage.setItem('data_stack', JSON.stringify(data_stack));

Retrieving the JSON and decoding it: 检索JSON并将其解码:

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');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM