gpt4 book ai didi

Javascript For..In 循环执行 if 和 else 语句

转载 作者:行者123 更新时间:2023-11-30 11:39:42 24 4
gpt4 key购买 nike

我有一个带有 else block 的 if 语句,它们都在 for in 循环中。当我执行它时,它总是返回 if 语句和 else 语句的值。当 if 语句为 false 时,它​​不应该只转到 else block 吗?

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

关于Javascript For..In 循环执行 if 和 else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43189370/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com