我可能需要编写一个函数,它只输出数组内对象的索引,显然,在下面的示例中使用 $.inArray 返回这个很好。
array = ['one', 'two', 'three'];
$.inArray('one', array) // 0
有了更复杂的数组,如何找到嵌套在其中的对象的索引?
array = [
{
name: 'One', // index??
data: {
title: 'Title One',
content: 'Content One'
}
},
{
name: 'Two',
data: {
title: 'Title Two',
content: 'Content Two'
}
},
{
name: 'Three',
data: {
title: 'Title Three',
content: 'Content Three'
}
}
];
我听说过 $.grep() 方法,indexOf() .. 不确定使用哪一个来返回对象所在索引的整数
最佳答案
您不需要预先编写的函数,只需遍历您的数组并比较 name
属性:
function findValue(array, nameWeAreLookingFor) {
for(var i = 0; i<array.length; i++) {
if(array[i].name === nameWeAreLookingFor) return i;
}
return -1;
}
关于javascript - 返回深度嵌套数组中对象索引的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11661297/