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

获取匹配条件的数组内对象的索引,第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');

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



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5620847.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存