javascript - 为什么我的 else if 语句不起作用?
问题描述
const yourIngredients = {
'spice rack': 'cinnamon',
'closet': 'flour',
'cabinet': 'brown sugar',
'fridge door': 'eggs',
'closet shelf': 'chocolate chips',
'lower cabinet': 'baking soda',
'drawer': 'yeast',
'cupboard': 'vanilla extract',
'table': 'salt',
'fridge': 'milk'
}
function bakingIngredients(ingredientYouNeed, locationsOfIngredients) {
for (let location in yourIngredients){
if (ingredientYouNeed === yourIngredients[location]){
return `You found ${yourIngredients[location]} in the ${location}`;
} else if(String(ingredientYouNeed) !== yourIngredients[location]) {
return "oof, you ran out :(";/*not working*/
}
}
}
console.log(bakingIngredients('flour', yourIngredients)) //--> You found flour in the closet
console.log(bakingIngredients('brown sugar', yourIngredients)) //--> You found brown sugar in the cabinet
console.log(bakingIngredients('cream cheese', yourIngredients)) //--> oof, you ran out :( /*not working*/
解决方案
您的示例都不应该起作用,因为您在第一次迭代时返回值,因此该函数只能检查第一个元素(仅'spice rack'
)。
在您遍历所有位置但未找到该元素之后,应该会出现表示您已用完某个元素的块。
像这样:
const yourIngredients = {
'spice rack': 'cinnamon',
'closet': 'flour',
'cabinet': 'brown sugar',
'fridge door': 'eggs',
'closet shelf': 'chocolate chips',
'lower cabinet': 'baking soda',
'drawer': 'yeast',
'cupboard': 'vanilla extract',
'table': 'salt',
'fridge': 'milk'
}
function bakingIngredients(ingredientYouNeed, locationsOfIngredients) {
for (let location in yourIngredients) {
if (ingredientYouNeed === yourIngredients[location]) {
return `You found ${yourIngredients[location]} in the ${location}`;
}
}
return "oof, you ran out :(";
}
console.log(bakingIngredients('flour', yourIngredients)) //--> You found flour in the closet
console.log(bakingIngredients('brown sugar', yourIngredients)) //--> You found brown sugar in the cabinet
console.log(bakingIngredients('cream cheese', yourIngredients)) //--> oof, you ran out :( /*not working*/
推荐阅读
- c - 如何避免链表的分段错误
- php - 为什么只有默认控制器在本地 WAMP 上的 CodeIgniter 中工作?
- azure - Azure SQL 无服务器数据库 cpu 不断计费
- java - 使用命令行从 pom.xml 获取依赖项的版本号,并使用该版本号标记 docker 映像
- apache-kafka - Apache Flink 中 KafkaProducer 的语义一次导致生产率低
- firebase - auth onCreate 触发器需要多长时间才能运行
- javascript - 用aCoords tl,br角而不是顶部绘制矩形,留在fabric.js中?
- swiftui - 小部件 SwiftUI 中的文本阴影不起作用
- javascript - 数据未在本机反应中使用 Flatlist 呈现
- c# - 使用 MixedReality-WebRTC 屏幕捕获