Bou*_*uke 5 javascript arrays indexof javascript-objects
在给定多个属性的情况下,获取对象数组中对象索引的最佳方法是什么?
想象一下以下示例数组:
var array = [
{
color: 'red',
shape: 'square',
weight: 200
},
{
color: 'blue',
shape: 'circle',
weight: 300
},
{
color: 'red',
shape: 'circle',
weight: 100
}
];
Run Code Online (Sandbox Code Playgroud)
现在我想拥有属性是和是indexOf的对象,在这个例子中,将是.colorredshapecircle2
理想情况下,该函数将在其属性的子集被给出时返回对象的索引,如果没有找到索引则{color: 'red', shape: 'circle'}返回-1。
在 ES6 中,有数组方法findIndex:
let index = array.findIndex(
element => element.color === 'red' && element.shape === 'circle'
);
Run Code Online (Sandbox Code Playgroud)
在那之前,坚持一个简单的迭代:
var index = -1; // -1 if not found
for (var i = 0; i < array.length; ++i)
{
var element = array[i];
if (element.color === 'red' && element.shape === 'circle')
{
index = i;
break;
}
}
Run Code Online (Sandbox Code Playgroud)