码迷,mamicode.com
首页 > 编程语言 > 详细

es6 数组实例的 find() 和 findIndex()

时间:2018-10-25 17:58:44      阅读:292      评论:0      收藏:0      [点我收藏+]

标签:cti   ret   def   null   define   indexof   bsp   es6   dex   

数组实例的find方法,用于找出第一个符合条件的数组成员。它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined。

[1, 4, -5, 10].find((n) => n < 0)
// -5
[1, 5, 10, 15].find(function(value, index, arr) {
return value > 9;
}) // 10

 上面代码中,find方法的回调函数可以接受三个参数,依次为当前的值、当前的位置和原数组。
数组实例的findIndex方法的用法与find方法非常类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。

[1, 5, 10, 15].findIndex(function(value, index, arr) {
return value > 9;
}) // 2

 这两个方法都可以接受第二个参数,用来绑定回调函数的this对象。
另外,这两个方法都可以发现NaN,弥补了数组的IndexOf方法的不足。

[NaN].indexOf(NaN)
// -1
[NaN].findIndex(y => Object.is(NaN, y))
// 0

 上面代码中,indexOf方法无法识别数组的NaN成员,但是findIndex方法可以借助Object.is方法做到。

 

现在ES6又加了一个Object.is,让比较运算的江湖更加混乱。多数情况下Object.is等价于“===”,如下;

在这之前我们比较值使用两等号 “==” 或 三等号“===”, 三等号更加严格,只要比较两方类型不同立即返回false。

1 === 1 // true
Object.is(1, 1) // true
 
‘a‘ === ‘a‘ // true
Object.is(‘a‘, ‘a‘) // true
 
true === true // true
Object.is(true, true) // true
 
null === null // true
Object.is(null, null) // true
 
undefined === undefined // true
Object.is(undefined, undefined) // true

 但对于NaN、0、+0、 -0,则和 “===” 不同

NaN === NaN // false
Object.is(NaN, NaN) // true
 
0 === -0 // true
Object.is(0, -0) // false
 
-0 === +0 // true
Object.is(-0, +0) // false

 

es6 数组实例的 find() 和 findIndex()

标签:cti   ret   def   null   define   indexof   bsp   es6   dex   

原文地址:https://www.cnblogs.com/bobo-site/p/9851238.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!