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');
與大多數優化一樣,只有在實際需要時才應謹慎應用。

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值),則還需要更新映射對象。

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。
添加回答
舉報