Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use find () and findIndex () in ES6

Shulou Source: shulou.com Published: 2022-06-01 03:46:58 09月22日 Update

This article mainly introduces how to use find () and findIndex () in ES6. It has a certain reference value. Interested friends can refer to it. I hope you can learn a lot after reading this article.

Find () and findIndex ()

The find method of the array instance, which is used to find the first qualified array member. Its argument is a callback function, which is executed by all array members in turn until the first member whose return value is true is found and then returned. If there are no eligible members, undefined is returned.

[1,4,-5,10] .find ((n) = > n)

< 0) // -5 [1, 5, 10, 15].find(function(value, index, arr) { return value >

9;}) / / 10

In the above code, the callback function of the find method can take three parameters, in turn, the current value, the current position, and the original array. The use of the findIndex method of an array instance is very similar to the find method, returning the position of the first qualified array member, or-1 if none of the members match the condition.

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

Both methods accept the second parameter, which is used to bind the this object of the callback function.

In addition, both methods can find NaN, which makes up for the deficiency of the IndexOf method of the array.

[NaN] .indexOf (NaN) / /-1 [NaN] .findIndex (y = > Object.is (NaN, y)) / / 0 Thank you for reading this article carefully. I hope the article "how to use find () and findIndex () in ES6" shared by the editor will be helpful to you. At the same time, I hope you will support us, pay attention to the industry information channel, and more related knowledge is waiting for you to learn!

Tags: Methods members arrays functions conditions articles parameters two locations instances three code value interest at the same time objects more friends knowledge editing Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Shulou Tech Info Redmi NVidia Huawei