相关文章推荐
刚毅的刺猬  ·  I want to dock my ...·  4 天前    · 
刚毅的刺猬  ·  BlockingCollection<t> ...·  2 月前    · 
刚毅的刺猬  ·  mysql ...·  10 月前    · 
刚毅的刺猬  ·  🤔 Failed to kill ...·  11 月前    · 
刚毅的刺猬  ·  通过插件创建 WordPress ...·  11 月前    · 
刚毅的刺猬  ·  C# ...·  11 月前    · 
不爱学习的火腿肠  ·  java ...·  1小时前    · 
旅行中的铁链  ·  错误信息:SSL ShakeHand ...·  1小时前    · 

Description

The findIndex() method executes a function for each array element.

The findIndex() method returns the index (position) of the first element that passes a test.

The findIndex() method returns -1 if no match is found.

The findIndex() method does not execute the function for empty array elements.

The findIndex() method does not change the original array.

Syntax

array .findIndex( function(currentValue, index, arr), thisValue )

Parameters

Parameter Description function() Required.
A function to be run for each array element. currentValue Required.
The value of the current element. index Optional.
The index of the current element. Optional.
The array of the current element. thisValue Optional. Default undefined .
A value passed to the function as its this value.

Return Value

Description Number The index of the first element that passes the test.
Otherwise -1.

Find the first element with a value above an input value:

<p><input type="number" id="toCheck" value="18"></p>

<button onclick="myFunction()">Test</button>

<p>Any values above: <span id="demo"></span></p>

<script>
const numbers = [4, 12, 16, 20];

function checkValue(x) {
return x > document.getElementById("toCheck").value;
}

function myFunction() {
document.getElementById("demo").innerHTML = numbers.findIndex(checkValue);
}
</script> Try it Yourself »

Related Pages:

Array Tutorial

Array Const

Array Methods

Array Sort

Array Iterations

Browser Support

findIndex() is an ECMAScript6 (ES6) feature.

ES6 (JavaScript 2015) is supported in all modern browsers:

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use , cookie and privacy policy .

W3Schools is Powered by W3.CSS .

 
推荐文章