JavaScript配列findIndex()
例1
18を超える値を持つ最初の要素を見つけます。
const ages = [3, 10, 18, 20];
ages.findIndex(checkAge);
function checkAge(age) {
return age > 18;
}
定義と使用法
このfindIndex()
メソッドは、配列要素ごとに関数を実行します。
このfindIndex()
メソッドは、テストに合格した最初の要素のインデックス(位置)を返します。
findIndex()
一致するものが見つからない場合、メソッドは-1を返します
。
このfindIndex()
メソッドは、空の配列要素に対して関数を実行しません。
このfindIndex()
メソッドは元の配列を変更しません。
構文
array.findIndex(function(currentValue, index, arr), thisValue)
パラメーター
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. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default undefined .A value passed to the function as its this value. |
戻り値
タイプ | 説明 |
数 |
テストに合格した最初の要素のインデックス。 それ以外の場合は-1。 |
ブラウザのサポート
findIndex()
ECMAScript6(ES6)機能です。
ES6(JavaScript 2015)は、最新のすべてのブラウザーでサポートされています。
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
findIndex()
Internet Explorer 11(またはそれ以前)ではサポートされていません。
その他の例
入力値を超える値を持つ最初の要素を見つけます。
<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>