• 获取某个数组元素 在 数组中的索引


    例如我们有数字:

    var arr1 =['aa','bb','cc','dd','ee','ff','gg','hh'];

    var arr2 = [

      {id:1,name:'lanyan'},

      {id:2,name:'wanming'},

      {id:3,name:'tingting'},

      {id:4,name:'songsong'}

    ];

    var arr2 = [

      {id:1,name:'lanyan'},

      {id:2,name:'wanming'},

      {id:3,name:'tingting'},

      {id:4,name:'songsong'},

      'test',

      'ethos'

    ];

    一般我们是通过indexOf,findIndex获取数组的索引的 

    arr1.indexOf('bb')  //1

    arr1.findIndex(function(data) {

      return data == 'bb';

    });

    //输出索引1 

    但是如果一个数组里 包含对象,也包含字符串呢,这里有一个函数供参考

    let getArrIndex = function(arr, obj) {
        let index = null;
        let key = Object.keys(obj)[0];
        arr.every(function(value, i) {
            if (value[key] === obj[key]) {
                index = i;
                return false;
            }
            return true;
        });
        return index;
    };

    用法:

    var getIndex = getArrIndex(arr2,{id:2,name:'wanming'});

    //输出:1

  • 相关阅读:
    2.7 矩阵的秩
    HDU
    HDU
    HDU
    HDU
    HDU
    hdu 5179 beautiful number(数位dp)
    ACdream
    CodeForces
    <a>标签中 href="/" 和 hideFocus="true"
  • 原文地址:https://www.cnblogs.com/laneyfu/p/6555519.html
Copyright © 2020-2023  润新知