gpt4 book ai didi

javascript - 如何通过在 forEach 循环中使用键返回我想要的对象?

转载 作者:行者123 更新时间:2023-11-29 23:13:55 25 4
gpt4 key购买 nike

考虑这段代码:

const year = 1910;

const items = [
{
name: 'gallon of gas',
year: 1910,
price: .12
},
{
name: 'gallon of gas',
year: 1960,
price: .30
},
{
name: 'gallon of gas',
year: 2010,
price: 2.80
}
]

如何显示与上面定义的年份对应的对象的价格?

items.forEach(d => {
if (d.year === year) {
return d.price;
}
});

^ 为什么该解决方案不起作用?

最佳答案

forEach()函数不返回值,无论您在回调函数中返回什么。使用 find()而不是找到符合您条件的项目:

const year = '1910';

const items = [
{
name: 'gallon of gas',
year: 1910,
price: .12
},
{
name: 'gallon of gas',
year: 1960,
price: .30
},
{
name: 'gallon of gas',
year: 2010,
price: 2.80
}
];

const item = items.find(i => i.year == year);

console.log(item.price);

注意:您不能在 find() 的回调中使用严格比较 (===),因为您正在比较年份 string 到年份 number。解决这个问题可能是个好主意。

关于javascript - 如何通过在 forEach 循环中使用键返回我想要的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53311197/

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