我有这个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