filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
array.filter(function(currentValue,index,arr), thisValue)
| 参数 | 描述 |
|---|---|
| currentValue | 必须。当前元素的值 |
| index | 可选。当前元素的索引值 |
| arr | 可选。当前元素属于的数组对象 |
| thisValue | 可选。对象作为该执行回调时使用,传递给函数,用作 “this” 的值。 如果省略了 thisValue ,”this” 的值为 “undefined” |
返回数组,包含了符合条件的所有元素。如果没有符合条件的元素则返回空数组。
写法一:
<button onclick="myFunction()">点我</button><p id="demo"></p>var ages = [32, 33, 16, 40];function myFunction() {document.getElementById("demo").innerHTML = ages.filter(function(ages){return ages >=18});}
写法二:
var ages = [32, 33, 16, 40];function checkAdult(age) {return age >= 18;}function myFunction() {document.getElementById("demo").innerHTML = ages.filter(checkAdult);}
注意: filter() 不会对空数组进行检测。
注意: filter() 不会改变原始数组。
