Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/456.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在forEach循环中使用键返回所需的对象?_Javascript - Fatal编程技术网

Javascript 如何在forEach循环中使用键返回所需的对象?

Javascript 如何在forEach循环中使用键返回所需的对象?,javascript,Javascript,考虑以下代码: 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 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;
   }
});

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

因为
return
语句位于函数
forEach
的处理程序内部,基本上,您返回的是处理程序执行,而不是主函数

您需要做的是使用for循环或函数
find
,如下所示:

let found = items.find(d => d.year === year);
if (found) return found.price;
或者是一个香草圈:

for (let i = 0; i < items.length; i++) 
   if (items[i].year === year) return items[i].price;
for(设i=0;i
无论您在回调函数中返回什么,函数都不会返回值。改为使用查找与您的条件匹配的项目:

const year='1910';
常数项=[
{
名称:“加仑汽油”,
年份:1910年,
价格:.12
},
{
名称:“加仑汽油”,
年份:1960年,
价格:.30
},
{
名称:“加仑汽油”,
年份:2010年,
价格:2.80
}
];
const item=items.find(i=>i.year==year);
控制台日志(项目价格)这需要ES6(巴别塔)。希望这有帮助!我从你那儿得到的

const year=1910;
常数项=[
{
名称:“加仑汽油”,
年份:1910年,
价格:.12
},
{
名称:“加仑汽油”,
年份:1960年,
价格:.30
},
{
名称:“加仑汽油”,
年份:2010年,
价格:2.80
}
]
常量值=对象值(项)
for(值的常量值){
//不能返回,但可以使用该值或将其存储在变量/数组中
console.log(value.price);

}
forEach()
不返回值。改为使用
find()
。听起来你只是想退货?因此,如果是这种情况,您应该查找
map(fn)
实用程序。示例:
items.map(item=>item.price)
'1910'==1910
将返回False抱歉,编辑了文章使其成为一个数字。1)在数组上调用
Object.values()
将只返回数组,因此您可以摆脱该问题,而不需要ES6。2) 您的解决方案打印出价格(与只执行
items.forEach(i=>console.log(i.price))
,它不会根据问题中提出的年份执行查找。