作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个带有 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/
我是一名优秀的程序员,十分优秀!