JavaScript 好用的数组查找方法
代码(部分ES6语法)
function findArray(array, feature, all = true) {
for (let index in array) {
let cur = array[index];
if (feature instanceof Object) {
let allRight = true;
for (let key in feature) {
let value = feature[key];
if (cur[key] == value && !all) return index;
if (all && cur[key] != value) {
allRight = false;
break;
}
}
if (allRight) return index;
} else {
if (cur == feature) {
return index;
}
}
}
return -1;
}
调用示例
var arr = [0, 1, 2, 3, 4, 5];
var index = findArray(arr, 5);
var arr = [{
id : '1',
name : 'cmx',
age : 23
},{
id : '2',
name : '习大大',
age : 60
}];
var index = findArray(arr, {id: '1'});
var index = findArray(arr, {id: '1', name: 'cmx'});
var index = findArray(arr, {id: '1', name: '习大大'}, false