亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

獲取數組內對象的索引,匹配條件

獲取數組內對象的索引,匹配條件

繁星coding 2019-09-19 09:59:27
我有這樣一個數組:[{prop1:"abc",prop2:"qwe"},{prop1:"bnmb",prop2:"yutu"},{prop1:"zxvz",prop2:"qwrq"},...]如何在不迭代整個數組的情況下獲取與條件匹配的對象的索引?例如,給定prop2=="yutu",我想獲得索引1。我看到.indexOf()但是認為它用于簡單的數組["a1","a2",...]。我也檢查了$.grep()但這會返回對象,而不是索引。
查看完整描述

3 回答

?
哆啦的時光機

TA貢獻1779條經驗 獲得超6個贊

截至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);

谷歌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');

與大多數優化一樣,只有在實際需要時才應謹慎應用。


查看完整回答
反對 回復 2019-09-19
?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

如何獲得與條件匹配的對象索引(不沿數組迭代)?


你不能,什么都有通過數組(至少一次)進行迭代。


如果條件變化很大,那么你將不得不循環并查看其中的對象以查看它們是否與條件匹配。但是,在具有ES5功能的系統上(或者如果安裝了墊片),可以相當簡潔地完成該迭代:


var index;

yourArray.some(function(entry, i) {

    if (entry.prop2 == "yutu") {

        index = i;

        return true;

    }

});

它使用new(ish)Array#some函數,它循環遍歷數組中的條目,直到你給它的函數返回true。我給它的函數保存了匹配條目的索引,然后返回true以停止迭代。


或者當然,只需使用for循環。您可以在其他答案中介紹各種迭代選項。


但是如果你總是要為這個查找使用相同的屬性,并且如果屬性值是唯一的,你可以只循環一次并創建一個對象來映射它們:


var prop2map = {};

yourArray.forEach(function(entry) {

    prop2map[entry.prop2] = entry;

});

(或者,您可以再次使用for循環或任何其他選項。)


然后,如果您需要找到條目prop2 = "yutu",您可以這樣做:


var entry = prop2map["yutu"];

我把這稱為“交叉索引”數組。當然,如果刪除或添加條目(或更改其prop2值),則還需要更新映射對象。


查看完整回答
反對 回復 2019-09-19
?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

var CarId = 23;


//x.VehicleId property to match in the object array

var carIndex = CarsList.map(function (x) { return x.VehicleId; }).indexOf(CarId);

對于基本數組編號,您也可以這樣做:


var numberList = [100,200,300,400,500];

var index = numberList.indexOf(200); // 1

如果在數組中找不到值,則會得到-1。


查看完整回答
反對 回復 2019-09-19
  • 3 回答
  • 0 關注
  • 1110 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號