首页 > 解决方案 > 如何使用 forEach 循环中的键返回我想要的对象?

问题描述

考虑这段代码:

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;
   }
});

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

标签: javascript

解决方案


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()因为您将年份字符串与年份数字进行比较。解决这个问题可能是个好主意。


推荐阅读