简体   繁体   English

具有全局变量的本地存储

[英]Local stroage with global variable

I am doing quiz show. 我在做测验节目。 If the user knows the questions, his money and his score will increase. 如果用户知道问题,他的钱和分数将增加。 At first, I gave them money and a score. 一开始,我给了他们钱和分数。 you know. 你懂。 and I keep the score and the money in the local depot. 我将分数和金钱保存在本地仓库中。 but when the game is reopened the money and score will be my first defined value. 但是当重新打开游戏时,金钱和分数将是我的第一个定义值。 how do I prevent it? 我该如何预防?

var cnt=1000;
var score = 0; 

cnt and score are the global variables. cnt和score是全局变量。 I use local storage. 我使用本地存储。

 localStorage.setItem("score ", score );
 localStorage.setItem("cnt", cnt);

When you give the right answer, 当您给出正确答案时,

if (deger == crntUserr) {
    DevExpress.ui.dialog.alert('Correct');
    cnt = cnt + 100;
    score = score + 10;
}

I do not want it to have an initial value 我不希望它有一个初始值

You should start the app while immediately reading your localStorage. 您应该在立即读取localStorage的同时启动该应用程序。

var cnt = Number(localStorage.getItem('cnt')) || 1000;
var score = Number(localStorage.getItem('score')) || 0; 

off course upon stopping the application or onChange 停止应用程序或onChange时偏离路线

if (deger == crntUserr) {
    DevExpress.ui.dialog.alert('Correct');
    cnt = cnt + 100;
    score = score + 10;

    // store the new value
    localStore.setItem('cnt', cnt);
    localStore.setItem('score', score);
}

You never update your localStorage value, so when restart app, they still have initial value so change your function to this : 您永远不会更新您的localStorage值,因此在重新启动应用程序时,它们仍然具有初始值,因此请将您的功能更改为:

if (deger == crntUserr) {
    DevExpress.ui.dialog.alert('Correct');

    var cntStorage= JSON.parse(localStorage.getItem('cnt'));
    var scoreStorage= JSON.parse(localStorage.getItem('score'));

    cnt = cntStorage + 100;
    score = scoreStorage + 10;

    localStorage.setItem('cnt', JSON.stringify(cnt));
    localStorage.setItem('score', JSON.stringify(score));
}

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

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