js數組中filter、map、reduce、find等方法實現的原理


filter用法和原理實現

filter 過濾,filter()使用指定的函數測試所有元素,並創建一個包含所有通過測試的元素的新數組。

用法

let arr=[2,4,6,8];
let arr1=arr.filter(function(item){
    return item>5
})
console.log(arr1) //[6,8]
let arr= [
    {id:1,name: "Alex", age: 18},
    {id:2,name: "Teamo", age: 15},
    {id:3,name: "Lily", age: 16},
    {id:4,name: "Lucy", age: 17},
    {id:5,name: "Tom", age: 19}
]
let arr1=arr.filter(function(item){
    return item.age>15
})
console.log(arr1)
//[ {id: 1, name: "Alex", age: 18},
{id: 3, name: "Lily", age: 16},
{id: 4, name: "Lucy", age: 17},
{id: 5, name: "Tom", age: 19}]

原理的實現

Array.prototype.filter1 = function (fn) {
  if (typeof fn !== "function") {
	throw new TypeError(`${fn} is not a function`);
  }
  let newArr = [];
	for(let i=0; i< this.length; i++) {
		fn(this[i]) && newArr.push(this[i]);
	}
	return newArr;
}
let arr=[2,4,6,8];
let arr1=arr.filter1(function(item){
    return item>5
})
console.log(arr1) //[6,8]

看完之后是不是so easy,其它的幾個實現大同小異,建議都手寫遍

map用法和原理實現

map 映射,map()方法返回一個新數組,數組中的元素為原始數組元素調用函數處理的后值。

用法

let arr = ['bob', 'grex', 'tom'];
let arr1 = arr.map(function(item) {
    return `<li>${item}</li>`;
});
console.log(arr1); //[ '<li>bob</li>', '<li>grex</li>', '<li>tom</li>' ]

原理實現

Array.prototype.map = function(fn) {
   if (typeof fn !== "function") {
	throw new TypeError(`${fn} is not a function`);
   }
    let newArr = [];
    for (let i = 0; i < this.length; i++) {
        newArr.push(fn(this[i]))
    };
    return newArr;
}

reduce用法和原理

reduce() 方法接收一個函數作為累加器,數組中的每個值(從左到右)開始縮減,最終計算為一個值。

用法

let arr=[2,4,6,8];
let result=arr.reduce(function (val,item,index,origin) {
    return val+item
},0);
console.log(result) //20

reduce原理實現

Array.prototype.reduce = function (reducer,initVal) {
    for(let i=0;i<this.length;i++){
        initVal =reducer(initVal,this[i],i,this);
    }
    return initVal
};

find用法和原理實現

find() 方法返回通過測試(函數內判斷)的數組的第一個元素的值。

用法

let arr = [1,2,3];
let arr1=arr.find(function (item) {
    return item>=2
});
console.log( arr5); //2

find原理實現

Array.prototype.find = function(fn) {
    if (typeof fn !== "function") {
	throw new TypeError(`${fn} is not a function`);
    }
    for (let i = 0; i < this.length; i++) {
        if (fn(this[i])) return this[i]
    }
}

some用法和原理實現

some() 方法會依次執行數組的每個元素:

如果有一個元素滿足條件,則表達式返回true , 剩余的元素不會再執行檢測。
如果沒有滿足條件的元素,則返回false。

用法

let arr = [2, 4, 6, 8];
let flag = arr.some(function(item) {
    return item > 5
});
console.log(flag); //true

some原理實現

Array.prototype.some=function (fn) {
    if (typeof fn !== "function") {
	throw new TypeError(`${fn} is not a function`);
    }
    for(let i=0;i<this.length;i++){
        if(fn(this[i])) {
            return true
        }
    }
    return false
};

every用法和原理實現

every方法用於檢測數組所有元素是否都符合指定條件(通過函數提供)。

用法

let arr = [2, 4, 6, 8];
let flag = arr.every(function(item) {
    return item > 5
});
console.log(flag); //false

原理實現

Array.prototype.every=function (fn) {
    if (typeof fn !== "function") {
	throw new TypeError(`${fn} is not a function`);
    }
    for(let i=0;i<this.length;i++){
        if(!fn(this[i])) {
            return false
        }
    }
    return true
};

經典前端面試題每日更新,歡迎參與討論,地址:https://github.com/daily-interview/fe-interview


更多angular1/2/4/5、ionic1/2/3、react、vue、微信小程序、nodejs等技術文章、視頻教程和開源項目,請關注微信公眾號——全棧弄潮兒

image

腦筋急轉彎:

image

生活小竅門

image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM