如何使用IndexOf方法获取JS对象数组中的索引

获得数组里某一个对象的索引的最佳方法是什么呢?

比如如下场景:

var hello = {
    hello: 'world',
    foo: 'bar'
};
var qaz = {
    hello: 'stevie',
    foo: 'baz'
}

var myArray = [];
myArray.push(hello,qaz);

现在我想得到hello属性值是stevie的对象的索引。在这个例子里,它是1

答案:

 使用map函数,一行帮你搞定

pos = myArray.map(function(e) { return e.hello; }).indexOf('stevie');

旁白:这行代码虽然简洁漂亮,而且真的使用到了indexOf函数,但是对于大数组,特别是频繁更新的大数组,那效率也忒低了点。于是有人提出findIndex才是更好的选择

另一个答案:

In ES2015, this is pretty easy:

myArray.map(x => x.hello).indexOf('stevie')

or, probably with better performance for larger arrays:

myArray.findIndex(x => x.hello === 'stevie')

 

posted @ 2023-05-16 09:03  Ning-  阅读(290)  评论(0编辑  收藏  举报