2016-06-19 40 views
0

我正在爲這節課寫下這個基本的控制結構,並且我得到了一些意想不到的行爲。檢查控制結構中是否有輸入

var answer = prompt('what is your age'); 
 

 
if (answer >= 21) { 
 
    alert('good to go!'); 
 
} 
 
else if (answer < 21) { 
 
    alert('sorry not old enough'); 
 
} 
 
else if (answer != typeof Number) { 
 
    alert('please enter your age as a number'); 
 
} 
 
else if (answer === null) { 
 
    alert('you did not answer!'); 
 
}

在最後的條件,我希望,如果我離開了提示空的,它會執行最後一次警報。但是,它只是說'不夠老'。它是否將提示輸入爲0?如何解決這個問題?

謝謝。如果用戶點擊OK

回答

0

提示不返回null,以測試空虛,你需要檢查,如果字符串爲空answer === ""

0

你需要最後兩個檢查移動到頂部,因爲"" < 21true

var answer = prompt('what is your age'); 
 

 
if (answer === '') { 
 
    alert('you did not answer!'); 
 
} else if (isNaN(answer)) { 
 
    alert('please enter your age as a number'); 
 
} else if (answer >= 21) { 
 
    alert('good to go!'); 
 
} else if (answer < 21) { 
 
    alert('sorry not old enough'); 
 
}