作用
- filter用于对数组进行过滤,可创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的元素
- 利用filter去除数组中重复元素,不会改变原数组
一、语法使用
let arr=Array.filter(function(currentValue, indedx, arr), thisValue)
currentValue:当前目标元素值
indedx:当前值下标
arr:需要过滤的目标数组
thisValue:一个可选参数,一个对象,作为该执行回调时使用,传递给函数,用作this的值。若省略了,this的值为undefinded
二、实例
1.filter用于对数组进行过滤,可创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的元素
//filter用于对数组进行过滤,可创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的元素
let arr1 = [1, 2, 3, 4, 5, 6];
let newArr = arr1.filter(item => {
return item >= 2;
})
console.log(newArr, 'newArr')
输出数组值
2.利用filter去除数组中重复元素,不会改变原数组
//利用filter去除数组中重复元素,不会改变原数组
let arr = ['red', 'yellow', 'green', 'red', 'pink', 'pink']
filterArr = arr.filter(function (item, index, arr) {
return arr.indexOf(item) == index
})
console.log(arr, 'arr');
console.log(filterArr, 'filterArr')
输出值