学习记录:ES6 数组扩展 - find, findIndex 和 includes

4 篇文章 0 订阅
4 篇文章 0 订阅

学习记录:ES6 数组扩展 - find, findIndex 和 includes

Array.prototype.find

  • 作用: 找出第一个符合查找条件的元素
  • 参数:一个回调函数 (item, index, array)=> { return … }
  • 返回值:符合条件的第一个元素,或者是 undefined
const list = [
  {
    label: 'red',
    value: 1
  },
  {
    label: 'blue',
    value: 2
  },
  {
    label: 'yellow',
    value: 3
  },
  {
    label: 'green',
    value: 2
  }
]

const findItem = function (list, value) {
  return list.find((item, index, array) => {
    return Object.is(item.value, value)
  })
}

const findItemEntrance = function (value) {
  return findItem(list, value)
}

findItemEntrance(2) // {label: 'blue', value: 2}
findItemEntrance(4) // undefined

ES5中,数组遍历查找的方法:Array.prototype.filter

    var num_1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    var newNum = num_1.filter(filterOne);

    function filterOne(x) {
      return x % 2 === 0;
    }
    // newNum 为 [2, 4, 6, 8, 10]
Array.prototype.find 和 Array.prototype.filter 的区别
  • 返回值:Array.prototype.find 符合条件的第一个元素,或者是 undefined,Array.prototype.filter 返回的就是一个数组
  • 应用场景不一样,只想找某一个元素,Array.prototype.find 就可以决解,若是找一类就需要生产新数组的迭代器 Array.prototype.filter

Array.prototype.findIndex

  • 作用: 找出第一个符合查找条件的元素的索引

  • 参数:一个回调函数 (item, index, array)=> { return … }

  • 返回值:符合条件的第一个元素的索引,否则返回 -1

let list = [1, 3, 6, 8]
let index = list.findIndex((item, index, array) => {
  return item >= 5
})
// index 为 2

let index = list.findIndex((item, index, array) => {
  return item >= 10
})
// index 为 -1

在 ES5 中有两个方法也是有来找出元素的索引:Array.prototype.indexOf 和 Array.prototype.lastIndexOf这两个方法已经很熟悉,来对比一下和 finindex 的区别:
#### 区别

  • 相同点:Array.prototype.indexOf 和Array.prototype. findIndex 都是获取与条件匹配的第一个元素,没有找到则返回 -1
  • 不同点:
    1. 参数,Array.prototype.findIndex 是一个回调函数,Array.prototype.indexOf 有两个参数,第一个是需要查找的元素,第二个参数从哪个位置开始查找
    2. 对于 NaN 的判断:
      • index 内部是用 === 取判断是否与条件匹配, 对于 NaN 会误判
      • findIndex 可自定义匹配条件,和 Objext.is() 一起使用可以成功判断是否为 NaN

Array.prototype.includes

  • 作用:判读一个元素是否在数组中
  • 返回值:Boolean

这个方法也是可以判断 NaN 是否存在 数组中,只能判断有没有,但是不能判断具体的位置。

let list = [1, 2, NaN, 4, 5, 6, NaN]
list.includes(NaN) // true

字符串也是有这个方法,作用类似。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值