我正在研究一個程序,我來到了一個點,我想循環一個值,然後用它來用if語句測試用戶的輸入,但問題是我無法使用循環的值。是否有替代JavaScript循環?
至少這就是我的想法,然後我試着將if語句作爲循環語句應該執行的代碼之一,令人驚訝的是它能夠工作,但是當我嘗試了更多的if語句時(例如,如果if ),它只執行我的一個if語句。
請問有沒有其他方法可以使用?
下面是代碼(輸入0到10之間的數字):
<input type="number" id="i" />
<input type="button" value="submit" onclick="result()" />
<p id="k"></p>
<script>
function result(){
//first method
var x= i.value;
var y = 0
while (y<10){
y++
}
if (x==y) {
document.getElementById("k").innerHTML = "correct"
}
/* it didn't work probably because the if statement assumes y to be 0. /*
//second method
while (y<10){
y++
if (x==y) {
document.getElementById("k").innerHTML = "correct"
}
else if (x >y) {
document.getElementById("k").innerHTML ="wrong"
}
}
//it only tested one of the if statement
</script>
或者是有循環的另一種方式呢?
你知道正確的值,爲什麼你循環任何事情? – dave
'while(y <10){y ++}'?那有什麼意義呢?這只是一個巨大的資源浪費版本'y = 10' –
如果我錯了,請告訴我一種替代方法 – Imran