例如我們有數字:
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