3 回答

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
截至2016年,您應(yīng)該使用Array.findIndex(ES2015 / ES6標(biāo)準(zhǔn)):
a = [
{prop1:"abc",prop2:"qwe"},
{prop1:"bnmb",prop2:"yutu"},
{prop1:"zxvz",prop2:"qwrq"}];
index = a.findIndex(x => x.prop2 ==="yutu");
console.log(index);
谷歌Chrome,F(xiàn)irefox和Edge支持它。對于Internet Explorer,鏈接頁面上有一個(gè)polyfill。
表現(xiàn)說明
函數(shù)調(diào)用很昂貴,因此對于非常大的數(shù)組,簡單的循環(huán)將比以下方式執(zhí)行得更好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');
與大多數(shù)優(yōu)化一樣,只有在實(shí)際需要時(shí)才應(yīng)謹(jǐn)慎應(yīng)用。

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個(gè)贊
如何獲得與條件匹配的對象索引(不沿?cái)?shù)組迭代)?
你不能,什么都有通過數(shù)組(至少一次)進(jìn)行迭代。
如果條件變化很大,那么你將不得不循環(huán)并查看其中的對象以查看它們是否與條件匹配。但是,在具有ES5功能的系統(tǒng)上(或者如果安裝了墊片),可以相當(dāng)簡潔地完成該迭代:
var index;
yourArray.some(function(entry, i) {
if (entry.prop2 == "yutu") {
index = i;
return true;
}
});
它使用new(ish)Array#some函數(shù),它循環(huán)遍歷數(shù)組中的條目,直到你給它的函數(shù)返回true。我給它的函數(shù)保存了匹配條目的索引,然后返回true以停止迭代。
或者當(dāng)然,只需使用for循環(huán)。您可以在其他答案中介紹各種迭代選項(xiàng)。
但是如果你總是要為這個(gè)查找使用相同的屬性,并且如果屬性值是唯一的,你可以只循環(huán)一次并創(chuàng)建一個(gè)對象來映射它們:
var prop2map = {};
yourArray.forEach(function(entry) {
prop2map[entry.prop2] = entry;
});
(或者,您可以再次使用for循環(huán)或任何其他選項(xiàng)。)
然后,如果您需要找到條目prop2 = "yutu",您可以這樣做:
var entry = prop2map["yutu"];
我把這稱為“交叉索引”數(shù)組。當(dāng)然,如果刪除或添加條目(或更改其prop2值),則還需要更新映射對象。

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超17個(gè)贊
var CarId = 23;
//x.VehicleId property to match in the object array
var carIndex = CarsList.map(function (x) { return x.VehicleId; }).indexOf(CarId);
對于基本數(shù)組編號,您也可以這樣做:
var numberList = [100,200,300,400,500];
var index = numberList.indexOf(200); // 1
如果在數(shù)組中找不到值,則會得到-1。
添加回答
舉報(bào)