我有這個if語句和else塊,它們都在for循環中。當我執行它時,它總是返回來自if語句和else語句的值。當if語句爲false時,它不應該僅僅到else塊嗎?Javascript For..In循環執行if和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>
它不是。你爲什麼認爲這是?這兩種方法都無法同時進行。它可能會在循環的不同迭代過程中完成每個循環,但這是不同的。 – Utkanos
您正在循環每個鍵。如果我輸入傷心,你會得到一次真實的,一次虛假的IF。 – yBrodsky
您正在使用您的moodList運行循環 - 因此您可以根據所有可能性檢查用戶輸入 - 它將記錄每個modd,如果它是您輸入的或不是的 – Danmoreng