Array.prototype.filter

2021-07-14  本文已影响0人  Lnevan

1.filter

1.1作用
1.2语法
Array.filter(function(element, indedx, arr), thisValue)
1.3实例
let nums = [1,44,2,5,3,34,65]
let newNums = nums.filter(item => {
  return item > 10
})
console.log(newNums) //[44,34,65]

2.实现filter

let nums = [1,44,2,5,3,34,65]
// console.log(newNums) //[44,34,65]
 Array.prototype.myFilter =  function (callback,thisValue) {
  if(this == undefined) { //null和undefined不能调用该方法
    throw new TypeError("this is null or not undefined!")
  }
  if(Object.prototype.toString.call(callback) != "[object Function]") { //判断传给callback的实参是否是函数,不是函数则报错
    throw new TypeError(callback + "is not a function!")
  }
  let res = [] //因为该方法不能改变原数组
                   //所以要新建一个数组来接收符合要求的数值
  for(let i = 0;i < this.length;i++) { //谁调用了该函数this就指向谁一个数组调用了该函数所以this.length相对于arr.length
    let right = callback.call(thisValue,this[i],i,this) //callback的this指向传来的thisValue,并且传参后面三个
    right && res.push(this[i]) //相与的特点:左边结果是true才会执行右边,false则跳过。这句的意思就是当right为true时(即符合用户在callback函数中所写的要求)再执行push操作
  }
  return res
}
let newNums = nums.myFilter(item => {
  return item > 10
})
console.log(newNums) //[44, 34, 65]
上一篇 下一篇

猜你喜欢

热点阅读