函数不会记住变量
Function won't remember variable
我想使用 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)) {
.
function addscore
是你痛苦的原因。您在其中添加了变量 score
,if 条件将引用该变量而不是全局变量。去掉它。您的函数定义应如下所示
function addscore() {
....
....
}
此外,为了在您的 if 条件中进行比较,请使用 ==
而不是用于分配的 =
。
换行
var score = score; //creates a global variable
类似于
var score = 0; //creates a global variable
因为分数目前还不存在。
我想使用 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)) {
.
function addscore
是你痛苦的原因。您在其中添加了变量 score
,if 条件将引用该变量而不是全局变量。去掉它。您的函数定义应如下所示
function addscore() {
....
....
}
此外,为了在您的 if 条件中进行比较,请使用 ==
而不是用于分配的 =
。
换行
var score = score; //creates a global variable
类似于
var score = 0; //creates a global variable
因为分数目前还不存在。