首页 > 解决方案 > 为什么我的 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*/

标签: javascriptif-statement

解决方案


您的示例都不应该起作用,因为您在第一次迭代时返回值,因此该函数只能检查第一个元素(仅'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*/


推荐阅读