gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:16:40 28 4
gpt4 key购买 nike

所以我正在根据我正在学习的类(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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com