Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么我的else if语句不起作用?_Javascript_If Statement - Fatal编程技术网

Javascript 为什么我的else if语句不起作用?

Javascript 为什么我的else if语句不起作用?,javascript,if-statement,Javascript,If Statement,您的示例都不应该工作,因为您在第一次迭代时返回值,因此函数只能检查第一个元素“spice rack” 表示元素已用完的块应该在遍历所有位置但未找到该元素后发生 像这样: 常数={ “香料架”:“肉桂”, “壁橱”:“面粉”, “内阁”:“红糖”, “冰箱门”:“鸡蛋”, “壁橱架”:“巧克力片”, “下柜”:“小苏打”, “抽屉”:“酵母”, “碗柜”:香草精, “表”:“盐”, “冰箱”:“牛奶” } 功能烘焙配料所需的配料、位置{ 让位置在你的配料{ 如果InCreditYouneed==

您的示例都不应该工作,因为您在第一次迭代时返回值,因此函数只能检查第一个元素“spice rack”

表示元素已用完的块应该在遍历所有位置但未找到该元素后发生

像这样:

常数={ “香料架”:“肉桂”, “壁橱”:“面粉”, “内阁”:“红糖”, “冰箱门”:“鸡蛋”, “壁橱架”:“巧克力片”, “下柜”:“小苏打”, “抽屉”:“酵母”, “碗柜”:香草精, “表”:“盐”, “冰箱”:“牛奶” } 功能烘焙配料所需的配料、位置{ 让位置在你的配料{ 如果InCreditYouneed==您的配料[位置]{ 返回“您在${location}中找到${yourComponents[location]}”; } } 返回oof,你跑出去了:; } 控制台。记录“面粉”,你的配料//>你在壁橱里发现了面粉 控制台。记录“红糖”,你的配料//->你在橱柜里发现了红糖
console.logbakinggreedients'cream cheese',yourmainments//->oof,your run:/*不起作用*/尝试一个简短的答案,说明我希望这段代码如何起作用,尽管在编写细节时还有些不清楚

您的问题源于您在烘焙过程中的循环始终在第一次迭代时返回。您需要将第二条语句移到循环之外,以便它仅在所有其他语句失败时用作回退,而不是在任何其他语句失败时

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*/

什么不起作用?在IngCreditYouRequired变量周围使用字符串的目的是什么?第二个if的目的是什么,而不仅仅是一个else?请更具体地说明您正在寻找的行为。
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 :(";/
}