作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我正在根据我正在学习的类(class)进行一个简单的 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`;
}
非常感谢任何帮助!这是一个艰难但有趣的学习过程!
谢谢!
最佳答案
您的代码按我的预期工作,因此问题可能在于您如何调用该函数或未显示的代码中的某些内容。
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' ));
关于Javascript For/in 循环不起作用 - 对象属性未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54691058/
我是一名优秀的程序员,十分优秀!