【问题标题】:Javascript For/in loop not working - Object property is not defined ErrorJavascript For/in 循环不起作用 - 对象属性未定义错误
【发布时间】:2021-11-02 15:07:44
【问题描述】:

所以我正在学习我正在学习的课程中的一个简单的 For/in 循环练习。 我们有一个具有 3 个属性的简单对象,我们必须创建一个带有 2 个参数的函数 - 对象名称和您要查找的项目。

我做了我的函数并与老师的解决方案进行了比较,它完全一样。问题是当我在控制台中尝试时,我得到一个错误,指责对象属性未定义。

代码如下:

// Question #2:
// Write a function checkBasket() that lets you know if the item is in the basket or not
const amazonBasket = {
  glasses: 1,
  books: 2,
  floss: 100
}

function checkBasket(basket, lookingFor) {
  for(item in basket) {
    console.log(item);
     if(item === lookingFor) {
      return `${lookingFor} is in your basket`;
    }     
   }
   return `${lookingfor} is not in your basket`;
}

非常感谢任何帮助!这是一个艰难但愉快的学习过程!

谢谢!

【问题讨论】:

  • 你必须调用函数!
  • 你有一个未定义的变量lookingfor在你最后一次返回你需要lookingFor
  • 大家好,感谢您的输入,但问题是当我调用函数时,我没有在引号之间写项目! :P 愚蠢的错误,但是讲座真的让我们对这个练习感到困惑,呵呵,谢谢你的帮助!

标签: javascript function object error-handling for-in-loop


【解决方案1】:

您的代码按我的预期工作,所以问题可能在于您如何调用函数或代码中未显示的内容。

PS:如果您使用数组而不是对象来存储项目,则可以使用 array.find() 或 array.indexOf() 等来使操作篮子更容易。

// Question #2:
// Write a function checkBasket() that lets you know if the item is in the basket or not
const amazonBasket = {
  glasses: 1,
  books: 2,
  floss: 100
}

function checkBasket(basket, lookingFor) {
  for(item in basket) {
    console.log(item);
     if(item === lookingFor) {
      return `${lookingFor} is in your basket`;
    }     
   }
   return `${lookingFor} is not in your basket`;
}

console.log( checkBasket( amazonBasket, 'floss' ));
console.log( checkBasket( amazonBasket, 'books' ));
console.log( checkBasket( amazonBasket, 'glasses' ));

const amazonBasket = [
  { "order_id": 1, "product_id": 13341544, "product_name": "glasses", "quantity": 1 },
  { "order_id": 1, "product_id": 12121321, "product_name": "books", "quantity": 5 },
  { "order_id": 1, "product_id": 47254114, "product_name": "floss", "quantity": 100 }
];

const checkBasket = ( basket, lookingFor ) => {
  const item = basket.find( item => item.product_name === lookingFor );
  if ( item ) return `${lookingFor} is in your basket`;
  else return `${lookingFor} is not in your basket`;
};

console.log( checkBasket( amazonBasket, 'floss' ));
console.log( checkBasket( amazonBasket, 'books' ));
console.log( checkBasket( amazonBasket, 'glasses' ));

【讨论】:

  • 感谢您抽出宝贵时间!你的代码/测试让我意识到我犯了一个愚蠢的错误,即在调用函数时没有在 lookingFor 项周围加上引号:P 谢谢你的帮助!
【解决方案2】:

您的代码在最后一行有错字:lookingfor 而不是lookingFor

【讨论】:

  • 感谢您发现这一点,阿列克谢!原来问题还在于调用该函数。调用该函数时,我没有将lookingFor 项目包含在引号中! :P
【解决方案3】:

刚刚进入课程的这一部分。对象应该是一个字符串。试试这样,放上代码后,调用函数是这样的:

checkBasket(amazonBasket, 'books')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    相关资源
    最近更新 更多