原生js实现filter,map,reduce方法

js原生封装一个filter方法

function myFilter(arr, callback) {
  if (!arr.length || !Array.isArray(arr) || typeof callback !== 'function') {
    return []
  } else {
    const result = []
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i]
      if (callback(item, i, arr)) {
        result.push(item)
      }
    }
    return result
  }
}
let arr = [1, 2, 3, 4, 5]
const res = myFilter(arr, (item, index, arr) => {
  console.log(item, index, arr)
  return item % 2 !== 0
})
console.log(res)  // [1, 3, 5]

js原生封装一个map方法

function myMap(arr, callback) {
  if (!arr.length || !Array.isArray(arr) || typeof callback !== 'function') {
    return []
  } else {
    const result = []
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i]
      result.push(callback(item, i, arr))
    }
    return result
  }
}
let arr = [1, 2, 3, 4, 5]
const res = myMap(arr, (item, index, arr) => {
  return item + 'aa'
})
console.log(res)  // ["1aa", "2aa", "3aa", "4aa", "5aa"]

js原生封装一个reduce方法

  • 无初始值

    function myReduce(arr, callback) {
      if (!Array.isArray(arr) || !arr.length || typeof callback !== 'function') {
        return []
      } else {
        let value = arr[0]
        for (let i = 1; i < arr.length; i++) {
    
          value = callback(value, arr[i], i, arr)
        }
        return value
      }
    }
    let arr = [1, 2, 3, 4, 5]
    const resMult = myReduce(arr, (value, item, i, arr) => {
      // console.log(value, item, i, arr)
      return value * item
    })
    const resAdd = myReduce(arr, (value, item, i, arr) => {
      // console.log(value, item, i, arr)
      return value + item
    })
    
    console.log(resMult, resAdd) // 120 15
    
  • 有初始值

    function myReduce(arr, callback, initVal) {
      if (!Array.isArray(arr) || !arr.length || typeof callback !== 'function') {
        return []
      } else {
        const isInit = initVal !== undefined
        let value = isInit ? initVal : arr[0]
        for (let i = isInit ? 0 : 1; i < arr.length; i++) {
          value = callback(value, arr[i], i, arr)
        }
        return value
      }
    }
    let arr = [1, 2, 3, 4, 5]
    const resMult = myReduce(arr, (value, item, i, arr) => {
      // console.log(value, item, i, arr)
      return value * item
    }, 0)
    const resAdd = myReduce(arr, (value, item, i, arr) => {
      // console.log(value, item, i, arr)
      return value + item
    }, 100)
    
    console.log(resMult, resAdd) // 0 115
    

你可能感兴趣的:(JS,面试题)