1. find()
find()
作用: 返回符合条件的数组项,如果没有返回undefind
Array.prototype.myFind = function(callback) {
for(var i = 0; i < this.length; i++) {
if(callback(this[i], i)) {
return this[i];
}
}
}
let arr = [
{id: 1, name: '刘备'},
{id: 2, name: '关羽'},
{id: 3, name: '张飞'}
]
let a = arr.myFind(function(ele, index) {
return ele.id == 4;
})
console.log(a)// undefined
2. findIndex()
findIndex()
作用: 返回符合条件的数组项的索引,如果没有返回-1
Array.prototype.myFindIndex = function(callback) {
for(var i = 0,len = this.length; i < len; i++) {
if(callback(this[i], i)) {
return i;
}else {
return -1;
}
}
}
let b = arr.myFindIndex(function(ele, index) {
return ele.id == 1;
})
console.log(b) // 0