英文:
localStorage variable in clicking game adds text instead of numbers to score, how to fix?
问题
我用JavaScript创建了一个点击游戏,并遇到了以下问题。我正在将一个变量定义为localStorage
项,但每次我点击应该将分数加一的按钮时,它都会将一个添加到文本的末尾。例如:[点击前:(1)点击后:(11)] 为什么会这样呢?
我的代码如下所示:
英文:
So I was creating a clicking game with JavaScript and ran into the following issue. I'm defining a variable to a localStorage
item, and every time I click the button that should add one to the score it adds one to the end of the text. For example: [before click: (1) after click: (11)] Why does it do this?
My code is provided in the image below:
答案1
得分: 1
当您从本地存储中检索数据时,您需要将其转换为数字,就像这样:
var Clicks = Number(localStorage.getItem('mystats'));
这是因为本地存储只能存储字符串。所以,在第2行从本地存储中获取点击次数时,如果点击次数是,例如,1,它返回 '1'
。 '1' + 1 == '11'
,这就是发生这种情况的原因。以下是另一个示例:
const x = '1';
console.log(x + 1); // 输出 '11'
console.log(Number(x) + 1); // 输出 2
英文:
When you retrieve the data from local storage, you need to convert it into a number, like this:
var Clicks = Number(localStorage.getItem('mystats');
This happens because local storage can only store strings. So, when you get the number of clicks from local storage on line 2, if the number of clicks is, for example, 1, it returns '1'
. '1' + 1 == '11'
, which is why this is happening. Here is another example:
<br/>
<br/>
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const x = '1';
console.log(x + 1); // logs '11'
console.log(Number(x) + 1); // logs 2
<!-- end snippet -->
答案2
得分: 1
你应该在增加它之前将localStorage.getItem
的结果转换为数字,像这样:
var Clicks = Number(localStorage.getItem("mystats"));
Clicks = Clicks + 1;
更多详情:
我认为你面临这个问题是因为localStorage
将所有值保存为字符串。
例如:如果你在控制台中运行以下命令:
localStorage.setItem("test", 123);
然后:
localStorage.getItem("test");
你将得到的值是:
"123"
如果你想将值作为数字获取,你需要将localStorage.getItem
的返回值转换为Number
:
const testValue = localStorage.getItem("test");
const testNumber = Number(testValue);
或者可以使用一行代码:
Number(localStorage.getItem("test"));
英文:
TLDR:
You should convert the result of localStorage.getItem
to a Number before incrementing it, like this:
var Clicks = Number(localStorage.getItem("mystats"));
Clicks = Clicks + 1;
More details:
I think you are facing this issue because localStorage
saves all the values as string
.
For example: if you run the following command in the console:
localStorage.setItem("test", 123);
and then:
localStorage.getItem("test");
the value you will get in return will be:
"123"
If you want to get the value as a number you would want to convert the return of localStorage.getItem
to Number
:
const testValue = localStorage.getItem("test");
const testNumber = Number(testValue);
or a one-liner:
Number(localStorage.getItem("test"));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论