我有一个带有else块的if语句,它们都在for循环中。当我执行它时,它总是返回if语句和else语句中的值。当if语句为false时,它是否只能转到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>
&#13;
答案 0 :(得分:2)
您可以检查输入的值是否是对象上的键,而不是在对象上创建循环:
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>
答案 1 :(得分:1)
您可以使用密钥并检查密钥是否在in
operator的对象中。
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 (moodInput in moodList) {
console.log('you got a result!');
} else {
console.log('nothing');
}
}
&#13;
<p>Click the button to begin</p>
<button onclick="myFunction()">Try it</button>
&#13;