javascript - 如何使用 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;
}
});
^ 为什么这个解决方案不起作用?
解决方案
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()
因为您将年份字符串与年份数字进行比较。解决这个问题可能是个好主意。
推荐阅读
- pandas - 根据列表替换子字符串
- javascript - 如何使用组元素删除以前的输入?
- css - Sass 选择器带 & 号,加上另一个类的 OR
- git - 远程:未找到存储库。在我自己的github上
- vue.js - 使用 v-slot 和 v-chip 不允许编辑芯片
- c++ - C++ std::maps 和带有构造函数的类值
- python - 如何让散景小部件与 plot .on_change() 交互
- laravel - 在 Laravel 中排除条件路由
- timestamp - 如何在 CockroachDB 中将 Unix 时间戳转换为日期?
- java - JPA/Hibernate:如何在同一会话中为具有 @Id 注释的字段保留重复值?