关于数组的map、filter、every、some、find、findIndex、 includesd几个方法实现原理
map方法 原理
//map 遍历格式所有项并返回一个新数组
Array.prototype.myMap = function(callback){
let arr = [];
for(let i = 0;i<this.length;i++){
arr.push(callback(this[i],i,this))
}
return arr
}
let arVal = [2,3,4];
console.log(arVal.myMap((item,index)=> item+1)); //[3, 4, 5]
filter方法 原理
//map 遍历格式所有项并返回一个新数组
Array.prototype.myFilter = function(callback){
let arr = [];
for(let i = 0;i<this.length;i++){
callback(this[i],i,this) && arr.push(this[i])
}
return arr
}
let arVal = [2,3,4,5];
console.log(arVal.myFilter((item,index)=> item>3)); //[4, 5]
every方法 原理
//every 遍历有项 有一个为false 则返回false 所有都为true 则为true
Array.prototype.myEvery = function(callback){
for(let i = 0;i<this.length;i++){
if(!callback(this[i],i,this)) return false
}
return true
}
let arVal = [2,3,4,5];
console.log(arVal.myEvery((item,index)=> item>3)); //false
some方法 原理
//some 遍历所有项 一项为true 就返回true 所有为false 则为false
Array.prototype.mySome = function(callback){
for(let i = 0;i<this.length;i++){
if(callback(this[i],i,this)) return true
}
return false
}
let arVal = [2,3,4,5];
console.log(arVal.mySome((item,index)=> item>3)); //true
find() 方法 原理
//find 遍历格式所有项并返回符合条件项 找不到返回undefined
Array.prototype.myFind = function(callback){
for(let i = 0;i<this.length;i++){
if(callback(this[i],i,this)) return this[i]
}
return undefined
}
let arVal = [2,3,4,5];
console.log(arVal.myFind((item,index)=> item === 3)); //3
findIndex() 方法原理
//findIndex 遍历所有项并返回符合判断条件项的索引 找不到返回-1
Array.prototype.myFindIndex = function(callback){
for(let i = 0;i<this.length;i++){
if(callback(this[i],i,this)) return i
}
return -1
}
let arVal = [2,3,4,5];
console.log(arVal.myFindIndex((item,index)=> item === 6)); //-1
includes() 方法 原理
//includes() 方法判断一个数组是否包含一个指定的值。
Array.prototype.myIncludes = function(argValue,start){
start = start < 0?this.length + start:start;
while( ++start < this.length){
if(this[start] === argValue || (this[start] !== this[start] && argValue !== argValue) ){
return true
}
}
return false
}
let arVal = [2,3,4,5];
console.log(arVal.myIncludes(3,0)); //true
let a = [NaN,undefined,null,NaN,1,2];
console.log(a.myIncludes(NaN,0));//true
console.log(a.myIncludes(9,0));//false
console.log(a.myIncludes(null,0));// true
console.log(a.myIncludes(undefined,0));// true
标签:
面试题
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本