gpt4 book ai didi

javascript - 函数不会记住变量

转载 作者:行者123 更新时间:2023-12-02 15:32:47 24 4
gpt4 key购买 nike

我想使用 JavaScript 创建一个记分板。我创建了一个 NaN 全局变量。我还创建了一个带有 if 语句的函数。如果变量为 NaN,则该变量需要为 0。然后该变量将得到 +1。当我单击按钮运行该函数时,结果为 1。但是当我重新单击该按钮并重新运行该函数时,结果仍为 1 并且不添加 +1。谁能告诉我我做错了什么?

var score = score; //creates a global variable
function addscore(score) {
alert(score); // just for me to see what value the variable has
if ((score) = isNaN) {
var score = 0; // the variable will be a number
}
score++;
alert(score);
}

最佳答案

通过将 score 作为函数的参数,您就声明了一个局部变量。您的函数在此局部变量而不是全局变量上运行,因此每次调用它时都必须向其传递一个值。

只需从函数声明中删除 score 即可:

function addscore() {

此外,这一行没有意义:

var score = score;

您无法将 score 设置为 score,因为 score 尚不存在!只要这样做:

var score = 0;

并且if ((score) = NaN) {将为score分配一个值。您想要检查值,例如 if (isNaN(score)) {

关于javascript - 函数不会记住变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33191199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com