JavaScript配列filter()
例1
18歳以上のages []のすべての値の配列を返します。
const ages = [32, 33, 16, 40];
const result = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
定義と使用法
このfilter()
メソッドは、関数によって提供されるテストに合格する要素で満たされた新しい配列を作成します。
このfilter()
メソッドは、空の要素に対して関数を実行しません。
このfilter()
メソッドは元の配列を変更しません。
構文
array.filter(function(currentValue, index, arr), thisValue)
パラメーター
Parameter | Description |
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. |
戻り値
タイプ | 説明 |
配列 |
テストに合格した要素が含まれています。 テストに合格する要素がない場合は、空の配列を返します。 |
ブラウザのサポート
filter()
ECMAScript5(ES5)機能です。
ES5(JavaScript 2009)は、すべてのブラウザーで完全にサポートされています。
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
例2
特定の数値を超えるages []の値を返します。
<p><input type="number" id="ageToCheck" value="30"></p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const ages = [32, 33, 12, 40];
function checkAge(age) {
return age > document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.filter(checkAge);
}
</script>