解析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的用法和實現原理

用法

過濾post

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 <this.length; i++) {
      if (callback(this[i])) {
        currentVal = this[i]
        break
      }
    }
    return currentVal
}
let result = [1,2,3,4]._find(item => item > 1)
console.log(result);  // 2
複製代碼

reduce的用法和實現原理

用法

累加ui

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的用法和實現原理

用法

只要有一個元素知足條件就返回truethis

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的用法和實現原理

用法

數組中每個元素知足條件就返回truespa

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 數組扁平化等 juejin.im/post/5cc80c…prototype

相關文章
相關標籤/搜索