Javascript For / in循环不起作用 - 未定义Object属性Error

问题描述 投票:0回答:2

所以我正在从我正在学习的课程开始一个简单的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`;
}

真的很感谢任何帮助家伙!这是一个艰难但令人愉快的学习过程!

谢谢!

javascript function object error-handling for-in-loop
2个回答
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
投票

你的代码在最后一行有一个拼写错误:寻找而不是寻找

© www.soinside.com 2019 - 2024. All rights reserved.