小编典典

获取匹配条件的数组内对象的索引

javascript

我有一个像这样的数组:

[{prop1:"abc",prop2:"qwe"},{prop1:"bnmb",prop2:"yutu"},{prop1:"zxvz",prop2:"qwrq"},...]

如何在不迭代整个数组的情况下获取与条件匹配的对象的索引?

例如,给定prop2=="yutu",我想获取index 1

我看到了,.indexOf()但认为它用于类似的简单数组["a1","a2",...]。我也检查了一下,$.grep()但这返回了对象,而不是索引。


阅读 443

收藏
2020-05-01

共1个答案

小编典典

从2016年开始,您应该为此使用Array.findIndex(ES2015 /
ES6标准):

a = [

  {prop1:"abc",prop2:"qwe"},

  {prop1:"bnmb",prop2:"yutu"},

  {prop1:"zxvz",prop2:"qwrq"}];



index = a.findIndex(x => x.prop2 ==="yutu");



console.log(index);

Google Chrome,Firefox和Edge支持该功能。对于Internet Explorer,在链接页面上有一个polyfill。

性能说明

函数调用是昂贵的,因此对于非常大的数组,简单的循环将比findIndex

let test = [];



for (let i = 0; i < 1e6; i++)

    test.push({prop: i});





let search = test.length - 1;

let count = 100;



console.time('findIndex/predefined function');

    let fn = obj => obj.prop === search;



    for (let i = 0; i < count; i++)

        test.findIndex(fn);

console.timeEnd('findIndex/predefined function');





console.time('findIndex/dynamic function');

    for (let i = 0; i < count; i++)

        test.findIndex(obj => obj.prop === search);

console.timeEnd('findIndex/dynamic function');





console.time('loop');

    for (let i = 0; i < count; i++) {

        for (let index = 0; index < test.length; index++) {

            if (test[index].prop === search) {

                break;

            }

        }

    }

console.timeEnd('loop');

与大多数优化一样,应谨慎且仅在实际需要时才应用此优化。

2020-05-01