2014-03-04 66 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; 
相關問題