簡體   English   中英

Javascript For..In循環執行if和else語句

[英]Javascript For..In loop executing both the if and else statement

我有一個帶有else塊的if語句,它們都在for循環中。 當我執行它時,它總是返回if語句和else語句中的值。 當if語句為false時,它不應該只轉到else塊嗎?

 <!DOCTYPE html> <html> <body> <p>Click the button to begin</p> <button onclick="myFunction()">Try it</button> <script> const moodList = { sad: { quotes: ['this is a sad quote', 'this is a sad quote number 2', 'this is a sad quote number 3' ] }, happy: { quotes: ['this is a happy quote', 'this is a happy quote number 2', 'this is a happy quote number 3' ] } } function myFunction() { let moodInput = prompt('Enter a feeling'); for (var key in moodList) { if (moodInput.includes(key)) { console.log('you got a result!'); } else { console.log('nothing'); } } } </script> </body> </html> 

您可以檢查輸入的值是否是對象上的鍵,而不是在對象上創建循環:

if (moodList[moodInput]) {
  console.log('you got a result!');
} else {
  console.log('nothing');
}

更新的代碼:

 const moodList = { sad: { quotes: ['this is a sad quote', 'this is a sad quote number 2', 'this is a sad quote number 3' ] }, happy: { quotes: ['this is a happy quote', 'this is a happy quote number 2', 'this is a happy quote number 3' ] } } function myFunction() { let moodInput = prompt('Enter a feeling'); if (moodList[moodInput]) { console.log('you got a result!'); } else { console.log('nothing'); } } 
 <p>Click the button to begin</p> <button onclick="myFunction()">Try it</button> 

您可以使用密鑰並使用in運算符檢查密鑰是否在對象in

 const moodList = { sad: { quotes: ['this is a sad quote', 'this is a sad quote number 2', 'this is a sad quote number 3' ] }, happy: { quotes: ['this is a happy quote', 'this is a happy quote number 2', 'this is a happy quote number 3' ] } }; function myFunction() { let moodInput = prompt('Enter a feeling'); if (moodInput in moodList) { console.log('you got a result!'); } else { console.log('nothing'); } } 
 <p>Click the button to begin</p> <button onclick="myFunction()">Try it</button> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM