解析js数组中的map,filter, reduce, find, some, every方法的实现原理

map的用法和实现原理

用法

"map"即"映射",也就是原数组被"映射"成对应新数组。

let arr = [1,2,3];
arr1 = arr.map(item => item * 2)

实现原理

Array.prototype._map = function (callback) {
let newArr = [];
for (let i = 0; i < this.length; i++) {
  newArr.push(callback && callback(this[i]))
}
return newArr
}
let result = [1,2,3]._map(item => item + 1)
console.log(result);  //[2, 3, 4]

filter的用法和实现原理

用法

过滤

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

实现原理

Array.prototype._filter = function (callback) {
let newArr = [];
for (let i = 0; i < this.length; i++) {
  callback && callback(this[i], i) && newArr.push(this[i])
}
return newArr
}

let filter = [1,2,3]._filter(item => item > 1) 
console.log(filter); // [2,3]

find的用法和实现原理

用法

该方法返回通过测试的数组的第一个元素的值

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

实现原理

Array.prototype._find = function (callback) {
    let currentVal
    for (let i = 0; i  item > 1)
console.log(result);  // 2

reduce的用法和实现原理

用法

累加

let arr=[2,4,6,8];
let arr1=arr.reduce((prev, item) => prev + item, 0)
console.log(arr1) // 20

实现原理

Array.prototype._reduce = function (callback, initVal) {
    for (let i = 0; i < this.length; i++) {
      initVal = callback(initVal, this[i], i, this)
    }
    return initVal
}
let result = [1,2,3,4]._reduce((prev, item) => prev + item, 0)
console.log(result);  // 10

some的用法和实现原理

用法

只要有一个元素满足条件就返回true

let arr = [1,2,3,4];
let res = arr.some(item => item > 4)
console.log(res);   // false

实现原理

Array.prototype._some = function (callback) {
// callback &&
let result = false
for (let i = 0; i < this.length; i++) {
  result = callback && callback(this[i])
}
return result
}
let result = [1,2,3]._some(item => item > 1)
console.log(result);  // true

every的用法和实现原理

用法

数组中每一个元素满足条件就返回true

let arr = [1,2,3,4];
let res = arr.every(item => item > 0)
console.log(res);   // true

实现原理

Array.prototype._every = function (callback) {
let result = true
for (let i = 0; i < this.length; i++) {
  if(!callback(this[i])) {
    result = false
    break
  }
}
return result
}
let result = [1,2,3]._every(item => item > 0)
console.log(result);  //true
let result = [1,2,3]._every(item => item > 1)
console.log(result);  //false

reduce实现filter,map 数组扁平化等 https://juejin.im/post/5cc80c6e6fb9a0324936c0d9

你可能感兴趣的:(解析js数组中的map,filter, reduce, find, some, every方法的实现原理)