JavaScript配列find()
例1
18を超える値を持つ最初の要素の値を見つけます。
const ages = [3, 10, 18, 20];
function checkAge(age) {
return age > 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAge);
}
定義と使用法
このfind()
メソッドは、テストに合格した最初の要素の値を返します。
このfind()
メソッドは、配列要素ごとに関数を実行します。
要素が見つからない場合、メソッドfind()
は再調整します。undefined
このfind()
メソッドは、空の要素に対して関数を実行しません。
このfind()
メソッドは元の配列を変更しません。
構文
array.find(function(currentValue, index, arr),thisValue)
パラメーター
function() | Required. A function to 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. |
戻り値
タイプ | 説明 |
価値 |
テストに合格した最初の要素の値。 それ以外の場合はを返します undefined 。 |
ブラウザのサポート
find()
ECMAScript6(ES6)機能です。
ES6(JavaScript 2015)は、最新のすべてのブラウザーでサポートされています。
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
find()
Internet Explorer 11(またはそれ以前)ではサポートされていません。
例2
特定の数値を超える値を持つ最初の要素の値を見つけます。
<p><input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const ages = [4, 12, 16, 20];
function checkAge(age) {
return age > document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAge);
}
</script>