Javascript For / in循环不起作用-未定义对象属性错误

时间:2019-02-14 13:02:03

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

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

我发挥了作用,并与老师的解决方案进行了比较,结果完全相同。问题是当我在控制台中尝试时,出现错误,提示未定义对象属性。

代码如下:

NotificationManager mNotificationManager =
        (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(SOMEID, mBuilder.build());

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

谢谢!

2 个答案:

答案 0 :(得分: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' ));

答案 1 :(得分:1)

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