js数组实例方法:filter,find,findIndex

Array.prototype.filter()

  • filter() 方法创建给定数组一部分的浅拷贝,其包含通过所提供函数实现的测试的所有元素
  • 语法
    • filter(callbackFn)
    • filter(callbackFn, thisArg)
  • 参数
    • callbackFn:为数组中的每个元素执行的函数。它应该返回一个真值以将元素保留在结果数组中,否则返回一个假值。该函数被调用时将传入以下参数:
      • element:数组中当前正在处理的元素
      • index:正在处理的元素在数组中的索引
      • array:调用了 filter() 的数组本身
    • thisArg:执行 callbackFn 时用作 this 的值
  • 返回值
    • 返回给定数组的一部分的浅拷贝,其中只包括通过提供的函数实现的测试的元素。如果没有元素通过测试,则返回一个空数组
  • Array.prototype.myFilter()
Array.prototype.myFilter = function (callbackFn, thisArg) {
  if (typeof callbackFn !== 'function') {
    throw new TypeError(`${typeof callbackFn} is not a function`)
  }
  const len = this.length,
    newArr = []
  let i = 0
  while (i < len) {
    if (this.hasOwnProperty(i) && callbackFn.call(thisArg, this[i], i, this)) {
      newArr.push(this[i])
    }
    i++
  }
  return newArr
}

Array.prototype.find()

  • find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined
  • 语法
    • find(callbackFn)
    • find(callbackFn, thisArg)
  • 参数
    • callbackFn:为数组中的每个元素执行的函数。它应该返回一个真值来表示已经找到了匹配的元素。该函数被调用时将传入以下参数:
      • element:数组中当前正在处理的元素
      • index:正在处理的元素在数组中的索引
      • array:调用了 find() 的数组本身
    • thisArg:执行 callbackFn 时用作 this 的值
  • 返回值
    • 数组中第一个满足所提供测试函数的元素的值,否则返回 undefined
  • Array.prototype.myFind()
Array.prototype.myFind = function (callbackFn, thisArg) {
  // 判断callbackFn类型,非函数报错
  if (typeof callbackFn !== 'function') {
    throw new TypeError(`${typeof callbackFn} is not a function`)
  }
  // 稀疏数组中,未赋值的空槽和undeifned表现相同
  let i = 0
  let len = this.length
  while (i < len) {
    // 找到元素的时候直接返回元素
    if (callbackFn.call(thisArg, this[i], i, this)) {
      return this[i]
    }
    i++
  }
  // 未找到,返回undefined
  return undefined
}

Array.prototype.findIndex()

  • findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1
  • 语法
    • findIndex(callbackFn)
    • findIndex(callbackFn, thisArg)
  • 参数
    • callbackFn:为数组中的每个元素执行的函数。它应该返回一个真值以指示已找到匹配元素,否则返回一个假值。该函数被调用时将传入以下参数:
      • element:数组中当前正在处理的元素
      • index:正在处理的元素在数组中的索引
      • array:调用了 findIndex() 的数组本身
    • thisArg:执行 callbackFn 时用作 this 的值
  • 返回值
    • 数组中第一个满足测试条件的元素的索引。否则返回 -1
  • Array.prototype.myFindIndex()
Array.prototype.myFindIndex = function (callbackFn, thisArg) {
  if (typeof callbackFn !== 'function') {
    throw new TypeError(`${typeof callbackFn} is not a function`)
  }
  const len = this.length
  for (let i = 0; i < len; i++) {
    if (callbackFn.call(thisArg, this[i], i, this)) {
      return i
    }
  }
  return -1
}

posted on   shenhf  阅读(12)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示