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。
添加回答
举报