返回深度嵌套数组中对象的索引的函数

2024-04-28

我可能需要编写一个函数,仅输出数组内对象的索引,显然,使用 $.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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

返回深度嵌套数组中对象的索引的函数 的相关文章

随机推荐