2014-03-04 69 views
1

我不明白为什么从数字变量减法不起作用。我的代码如下。减法不适用于一个变量

function Check() { 
var Viewer = document.getElementById("Viewer"); 
var TrysLeft = 3; 
    if (Viewer.value == Num) { 
    alert("Correct"); 
    } else { 
    TrysLeft - 1; 
    alert("Sorry you got the combo wrong! You have " + TrysLeft + " Trys left before the combo is reset"); 
    } 
} 

回答

1

首先,纠正行:

TrysLeft = -1;

由:

TrysLeft -= 1;

下一页:

可以使用封闭每个函数被调用时保持变量的当前值:

var TrysLeft = 3; 

function Check() { 
var Viewer = document.getElementById("Viewer"); 
    if (Viewer.value == Num) { 
    alert("Correct"); 
    } else { 
    `TrysLeft -= 1;` 
    alert("Sorry you got the combo wrong! You have " + TrysLeft + " Trys left before the combo is reset"); 
    } 
} 
+3

这只是改变的变量 - 1 – CDW

+1

的答案删除空格,以便它的'TrysLeft - = 1' – SparkyRobinson

2

你有var TrysLeft = 3;作为一个局部变量。每次调用该函数时,它都会重新初始化为3。

你也没有分配TrysLeft任何东西后,你减去它。 你可以做TrysLeft--;TrysLeft = TrysLeft -1;

+0

谢谢你,解决了我的问题。 – CDW

+0

@Kevin好眼睛! – Edper

2

它应该是:

TrysLeft = TrysLeft - 1; 

或者

TrysLeft -= 1; 
+0

这与'TrysLeft - ;'相同,这是更少的代码。 – PHPglue

+0

我同意你@PHPglue。我正要改变它,但你也有它的答案。 – Edper

2

尝试使用下面的代码:

TrysLeft--; 

--TrysLeft; 

此外,我建议保持变量小写,这不是函数或对象。

1

也许你可以尝试

TrysLeft=TrysLeft-1; 
相关问题