この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