我在 javascript 中有一个像这样的对象数组:
var events =
[
{
id: 'a',
title: 'Event 1 title'
},
{
id: 'b',
title: 'Event 2 title'
}
];
为了引用事件 b,我必须知道事件 b 的索引,可以通过循环遍历数组并检查当事件的 id 与 b 匹配时事件的索引来找到该索引。
当我知道事件的 id 属性时,是否有更简单的方法来引用事件 b?
最佳答案
In order to reference event b I have to know the index of the event b
不一定。您可以使用Array.filter
来获取您需要的对象,而无需知道它的索引。
var obj = events.filter(function(obj){
return obj.id == "b";
})[0]
或者你也可以使用ES6中新增的Array.prototype.find
,例如
var obj = events.find((obj) => obj.id == "b");
关于javascript - 引用对象(在数组中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32295580/