js array方法实现

map

function _map (arr, cb) {
  const _arr = []
  for (let i = 0; i < arr.length; i++) {
    _arr.push(cb(arr[i], i))
  }
  return _arr
}

const arr = _map([1, 2, 3, 4, 5], function (item, index) {
  console.log(index)
  return item * 2
})
console.log(arr)

filter

function _filter (arrs, cb) {
  const result = []
  for (let index = 0; index < arrs.length; index++) {
    if (cb(arrs[index])) {
      result.push(arrs[index])
    }
  }
  return result
}

const arr = _filter([1, 2, 3, 4, 5], function (item) {
  return item > 3
})

console.log(arr)

find

function _find (array, cb) {
  for (let index = 0; index < array.length; index++) {
    if (cb(array[index])) {
      return [array[index]]
    }
  }
}

const arr = _find([1, 2, 3, 4, 5], function (item) {
  return item > 3
})

console.log(arr)

findIndex

function _findIndex (array, callback) {
  for (let index = 0; index < array.length; index++) {
    if (callback(array[index])) { return index }
  }
}

const res = _findIndex([1, 2, 3, 4, 5], (item) => {
  return item === 3
})
console.log(res)

你可能感兴趣的:(js array方法实现)