1. find()
find():
查找目标元素,找到就返回该元素,找不到返回undefined。
var users = [
{id: 1, name:"李四"},
{id: 2, name:"张三"},
{id: 3, name:"王五"},
{id: 4, name:"小小"}
];
Array.prototype.myFind = function(condition){
//condition(function(item,index){return item.name === 4})
for(var i = 0; i < this.length; i++){
//判断 condition(this[i]) 是否为true
//调用 myFind() 后,接收到返回值 item.name === "张三"
//所以为判断 this[i].name === "张三" 是否为true
//为true 返回该元素
if(condition(this[i].i)){
return this[i]
}
}
};
var ret = users.myFind(function(item,index){
return item.name === "张三"
});
console.log(ret);
2. findIndex()
findIndex():
查找目标元素,找到就返回元素的位置,找不到就返回-1。
var users = [
{id: 1, name:"李四"},
{id: 2, name:"张三"},
{id: 3, name:"王五"},
{id: 4, name:"小小"}
];
Array.prototype.myFind = function(condition){
//condition(function(item,index){return item.name === 4})
for(var i = 0; i < this.length; i++){
//判断 condition(this[i]) 是否为true
//调用 myFind() 后,接收到返回值 item.name === "张三"
//所以为判断 this[i].name === "张三" 是否为true
//为true 返回该元素的索引值
if(condition(this[i],i)){
return i
}
}
};
var ret = users.myFind(function(item,index){
return item.name === "张三"
});
console.log(ret);