我正在為我的一個課程做一個專案,我需要使用用戶輸入將他們重定向到一個網站。它要求使用回圈驗證用戶的選擇,因此我選擇使用 while 回圈來檢查用戶輸入是否與應有的不同,如果是,則提示用戶重新輸入他們的答案. 這是代碼:
var websitechoice;
websitechoice = parseInt(prompt("Which website would you like to go to? \n 1. google \n 2. gmail \n 3. youtube"))
while (websitechoice != 1 || 2 || 3) {
alert("you input an incorrect value")
websitechoice = parseInt(prompt("Which website would you like to go to? \n 1. google \n 2. gmail \n 3. youtube"))
}
if (websitechoice = 1) {
alert("you chose 1")
}
else if (websitechoice = 2) {
alert("you chose 2")
}
else {
alert("you chose 3")
}
到目前為止,這只是我為檢查它是否可以作業而制作的一個快速模型,但每次我嘗試運行它時,即使輸入 1、2 或 3,我總是會回傳“你輸入了不正確的值”,等等到目前為止,我嘗試過的任何結果都沒有不同。如果有人可以提供幫助,我將不勝感激,謝謝
uj5u.com熱心網友回復:
您在 if 陳述句中使用了定義,因為您告訴代碼 websitechoice 現在等于該數字。你應該像這樣使用比較器
if (websitechoice == 1) {
alert("you chose 1")
}
else if (websitechoice == 2) {
alert("you chose 2")
}
else {
alert("you chose 3")
}
對于您的 while 陳述句,您應該將其更改為 and 陳述句,因為您只想在它不等于 1且不等于2且不等于 3時運行代碼
while (websitechoice != 1 && websitechoice != 2 && websitechoice != 3) {
alert("you input an incorrect value")
websitechoice = parseInt(prompt("Which website would you like to go to? \n 1. google \n 2. gmail \n 3. youtube"))
}
您也可以只說,if websitechoice > 3然后執行警報程序
uj5u.com熱心網友回復:
你的代碼有很多缺陷。首先,您應該使用 AND 運算子而不是 OR 運算子。此外,您需要像 beloe 演示的那樣打破比較。
其次,您在 if else 陳述句中使用了賦值運算子 ( = )。您需要使用比較運算子( == 或 === )進行比較,否則每次都會回傳 1。
var websitechoice;
websitechoice = parseInt(prompt("Which website would you like to go to? \n 1. google \n 2. gmail \n 3. youtube"))
while (websitechoice !== 1 && websitechoice !== 2 && websitechoice !== 3) {
alert("you input an incorrect value")
websitechoice = parseInt(prompt("Which website would you like to go to? \n 1. google \n 2. gmail \n 3. youtube"))
}
if (websitechoice === 1) {
alert("you chose 1")
}
else if (websitechoice === 2) {
alert("you chose 2")
}
else {
alert("you chose 3")
}
此外,如果您將代碼放在代碼段中,將很容易除錯。似乎您對開發人員社區很陌生。歡迎來到程式員社區!
uj5u.com熱心網友回復:
!= 優先于 || 運營商1所以:
websitechoice != 1 || 2 || 3
將始終評估為:
(websitechoice != 1) || 2 || 3
這不是你想要的......
另一個問題是:
websitechoice = 1
是分配而不是比較。
要在不更改其結構的情況下修復代碼:
var websitechoice;
websitechoice = parseInt(prompt("Which website would you like to go to? \n 1. google \n 2. gmail \n 3. youtube"))
while (websitechoice !== 1 && websitechoice !== 2 && websitechoice !== 3) {
alert("you input an incorrect value")
websitechoice = parseInt(prompt("Which website would you like to go to? \n 1. google \n 2. gmail \n 3. youtube"))
}
if (websitechoice === 1) {
alert("you chose 1")
}
else if (websitechoice === 2) {
alert("you chose 2")
}
else {
alert("you chose 3")
}
檢查您的輸入是否是值串列之一的更簡潔的方法可能是:
[1,2,3].includes(websitechoice)
它更干凈,可以輕松擴展到更多值。
我還用 , 替換了==運算子,除非你知道自己在做什么,否則 ===不要在 JS 中使用。2==
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/476462.html
標籤:javascript while循环 迅速的
上一篇:如何從SQL中讀取資料并將其放入VB中的陣列中,其中包含代碼且沒有框
下一篇:如何使用陣列和DOM更改文本
