js中数组find方法的使用和实现find方法定义find ) )方法返回数组中满足所传递函数条件的第一个元素的值。 否则我要回undefined。
find方法语法arr.find(callback(element[,index[,selfArr]] ) {},thisArg] )
find方法参数callback
在数组的每个项目中执行的函数接收以下三个参数:
)1)element
当前正在遍历的元素。
)2)index选项
当前正在遍历的索引。
)3)array选项
调用find方法的数组本身。thisArg选项
在执行callback回调时用作this的对象。
find方法返回数组中第一个满足所传递callback函数的元素的值,否则返回undefined。
find方法对数组中的每个元素执行一次callback函数,详细说明直到一个callback返回true。 如果发现这样的元素,方法将立即返回该元素的值,否则返回undefined。
请注意,callback函数不仅为分配的索引调用,而且为数组中的每个索引调用0到length - 1。 (这与映射和过滤器等方法有所区别。)
callback函数有三个参数:当前元素的值、当前元素的索引和数组本身。
如果指定了thisArg参数,则每次运行callback函数时都将用作this,否则将使用undefined。 (this的指向取决于this的指向规则)
find方法不更改原始数组。
由于第一次调用callback函数时会确定元素的索引范围,因此callback函数不会访问在find方法开始执行后添加到数组中的新元素。 如果数组中未被callback函数访问的元素的值被callback函数更改,则在访问callback函数时,该值将成为数组中索引访问的当前值。 已删除的元素仍被访问,但其值已被取消定义。
使用示例查询大于3的元素
letarr=[ 0,1,4]constreasult=arr.find((m,index )={console.log ),index} ) return m 3 } ) console ind index: 1} //{m: undefined,index:}//{m:undefined,index3360}/打印原始数组arr没有任何更改。
获取数组中的对象
let arr2=[ { name: 'kat' },{ name : ' dog ' } ] constreasult2=arr2. find ((element,index ) ) console.lond index } (返回元素. name===' kat ' ) console.log ) reasult2)//{ element : { name : ' kat ' },index3360
想法1,把myFind方法挂在数组的原型上
2、获取原始数组的长度
3、用call方法调用callback函数的this进行更改
4、判断acllback函数的返回值,返回当前元素
代码array.prototype.my find=function (callback,thisArg ) ) letlength=this.lengthfor ) letindex=0; 索引长度; index () if ) callback.call ) thisArg,this[index],index,this ) }测试验证Array.prototype.my index length; index () if ) callback.call ) thisarg,this[index],index,this ) ) return this [ index ] } letarr=[ 0,1,4 ] 索引((console.log ) element,index ) ) return element 3 } ) console.log ) reasult,arr )/) m:index 3360索引index: 2} //{m: undefined,index: 3} //{m: 4,index3360}//4 4 ) letARR2=[name:'kat'},{ n index } (返回元素. name===' kat ' ) console.log ) reasult2)//{ element : { name : ' kat ' },index3360