1. Es6 中find用法
find() 方法返回数组中满足提供的测试函数的第一个元素的值 否则返回undefined
var number = [ 5 , 12 , 8 , 130 , 44 ] ;
var found = number. find ( function ( element) {
return element > 10 ;
} ) ;
console. log ( found) ;
查找符合条件的指定元素
var inventory = [
{ name: 'apples' , quantity: 2 } ,
{ name: 'bananas' , quantity: 0 } ,
{ name: 'cherries' , quantity: 5 }
] ;
name = inventory. find ( function ( element) {
return element. name === 'cherries' ;
} ) ;
console. info ( name) ;
查找元素,返回找到的值,找不到返回undefined
const arr1 = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ] ;
var ret1 = arr1. find ( ( value, index, arr) => {
return value > 4
} )
var ret2 = arr1. find ( ( value, index, arr) => {
return value > 14
} )
console. log ( '%s' , ret1)
console. log ( '%s' , ret2)
5
undefined
2. findIndex 查找元素返回索引
查找元素 返回找到的index, 找不到返回 -1
var ret3 = arr1. findIndex ( ( value, index, arr) => {
return value > 4
} )
var ret4 = arr1. findIndex ( ( value, index, arr) => {
return value > 14
} )
console. log ( '%s' , ret3)
console. log ( '%s' , ret4)
结果:
4
- 1
3. 实现方式
var users = [
{ id: 1 , name: '张三' } ,
{ id: 2 , name: '张三' } ,
{ id: 3 , name: '张三' } ,
{ id: 4 , name: '张三' }
]
Array. prototype. myFind = function ( conditionFunc) {
for ( var i = 0 ; i < this . length; i++ ) {
if ( conditionFunc ( this [ i] , i) ) {
return this [ i]
}
}
}
var ret = users. myFind ( function ( item, index) {
return item. id === 2
} )
console. log ( ret)