[英]How do I return the object I want by using a key in a forEach loop?
Consider this code:考虑这个代码:
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
}
]
How do I display the price of the object corresponding to the year defined above?如何显示与上面定义的年份对应的对象的价格?
items.forEach(d => {
if (d.year === year) {
return d.price;
}
});
^ Why doesn't that solution work? ^ 为什么那个解决方案不起作用?
The forEach()
function doesn't return a value, regardless of what you return in the callback function.无论您在回调函数中返回什么,
forEach()
函数都不会返回值。 Use find()
instead to find the item that matches your criteria:使用
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);
Note: you can't use strict comparison ( ===
) in the callback to find()
because you're comparing a year string to a year number .注意:您不能在
find()
的回调中使用严格比较 ( ===
),因为您将年份字符串与年份数字进行比较。 Probably a good idea to address that.解决这个问题可能是个好主意。
Because that return
statement is inside of the handler of the function forEach
, basically, you're returning the handler execution and not the main function.因为该
return
语句位于函数forEach
的处理程序内,所以基本上,您返回的是处理程序执行而不是主函数。
What you need to do is either to use a for-loop or the function find
as follow:您需要做的是使用 for 循环或函数
find
如下:
let found = items.find(d => d.year === year);
if (found) return found.price;
Or a vanilla for-loop:或香草 for 循环:
for (let i = 0; i < items.length; i++)
if (items[i].year === year) return items[i].price;
This needs ES6 (babel).这需要 ES6 (babel)。 Hope this helps!
希望这可以帮助! Got it from https://zellwk.com/blog/looping-through-js-objects/ .
从https://zellwk.com/blog/looping-through-js-objects/得到它。
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 values = Object.values(items) for (const value of values) { //you can't return, but you can use the value or store it in a variable/array console.log(value.price); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.