Home  >  Article  >  Web Front-end  >  Detailed explanation of the usage of Array.find() and findIndex() functions in ES6

Detailed explanation of the usage of Array.find() and findIndex() functions in ES6

巴扎黑
巴扎黑Original
2018-05-15 10:44:416500browse

ES6 adds find() and findIndex functions to Array. The find() function is used to find the target element. If it is found, it will return the element. If it is not found, it will return undefined. The findIndex() function also searches for the target element. If it is found, it will return the position of the element. If it is not found, it will return -1. The following is a detailed explanation through examples. Friends who need it can refer to it

ES6 adds find() and findIndex functions to Array.

The find() function is used to find the target element. If it is found, it returns the element. If it cannot find it, it returns undefined.

The findIndex() function also searches for the target element. If it is found, it returns the position of the element. If it is not found, it returns -1.

They are all a search callback function.

[1, 2, 3, 4].find((value, index, arr) => {
})

The search function has three parameters.

value: The array element searched for each iteration.

index: The array element index searched for each iteration.

arr: The array being searched.

Example:

1. Search for elements and return the found value. If not found, undefined is returned.

const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
var ret1 = arr1.find((value, index, arr) => {
 return value > 4
})
var ret2 = arr1.find((value, index, arr) => {
 return value > 14
})
console.log('%s', ret1)
console.log('%s', ret2)

Result:

undefined

2. Find the element and return the found index. If not found, return -1.

var ret3 = arr1.findIndex((value, index, arr) => {
 return value > 4
})

var ret4 = arr1.findIndex((value, index, arr) => {
 return value > 14
})
console.log('%s', ret3)
console.log('%s', ret4)

Result:

4
-1

3. Find NaN.

const arr2 = [1, 2, NaN, 4, 5, 6, 7, 8, 9, 10, 11]
var ret5 = arr2.find((value, index, arr) => {
 return Object.is(NaN, value)
})
var ret6 = arr2.findIndex((value, index, arr) => {
 return Object.is(NaN, value)
})
console.log('%s', ret5)
console.log('%s', ret6)

Result:

NaN
2

The above is the detailed content of Detailed explanation of the usage of Array.find() and findIndex() functions in ES6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn