定义和用法
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
注意: filter() 不会对空数组进行检测。
注意: filter() 不会改变原始数组。
语法
array.filter(function(currentValue,index,arr), thisValue)
参数说明
参数 | 描述 | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index,arr) | 必须。函数,数组中的每个元素都会执行这个函数 函数参数:
| ||||||||
thisValue | 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。 如果省略了 thisValue ,"this" 的值为 "undefined" |
实例
返回数组中所有年龄大于18的元素集合
let sunArr = [{
id: '1',
name: 'lee',
age: '20'
}, {
id: '2',
name: 'sun6sian',
age: '24'
}]
newArr = sunArr.filter((item, index, arr) => item.age > 18)
结果是