例如我们有数字:
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