简体   繁体   中英

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

I have this if statement with an else block and they are both inside a for in loop. When I execute this it always return both the value from the if statement and the else statement. Shouldn't it only go to the else block when the if statement is false?

 <!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> 

Instead of creating a loop over the object, you could check to see if the value entered is a key on the object:

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

Updated Code:

 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> 

You could use the key and check if the key is in the object with the in operator .

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM