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

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

[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方法作到。this

 

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

在这以前咱们比较值使用两等号 “==” 或 三等号“===”, 三等号更加严格,只要比较两方类型不一样当即返回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,则和 “===” 不一样blog

NaN === NaN // false
Object.is(NaN, NaN) // true
 
0 === -0 // true
Object.is(0, -0) // false
 
-0 === +0 // true
Object.is(-0, +0) // false
相关文章
相关标签/搜索