前端手写(十)——手写数组方法filter

x33g5p2x  于2022-03-31 转载在 其他  
字(0.5k)|赞(0)|评价(0)|浏览(350)

一、写在前面
filter方法存在两个参数,第一个参数是一个回调函数,第二个参数是回调函数中的this指向,第二个参数是可以不传的。
二、手写

在写之前我们需要注意一下几点:
1、callback必须是函数,如果不是函数则直接报错。
2、调用该方法的必须是数组,如果不是数组,则直接报错。
3、如果数组的长度为0,则直接返回空数组。
Array.prototype.myFilter = function (callback, thisArg) {
  let length = this.length
  let res = []
  if (!Array.isArray(this)) throw new TypeError('this is not an array')
  if (typeof callback !== 'function') throw new TypeError(callback + 'is not a function')
  if (length === 0) return res
  for (let i = 0; i < length; i++) {
    if (callback.call(thisArg, this[i], i, this)) {
      res.push(this[i])
    }
  }
  return res
}

相关文章

微信公众号

最新文章

更多