數組實例的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