关于数组的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

posted @ 2023-02-23 16:50  巫小婆  阅读(27)  评论(0编辑  收藏  举报