fliter()方法是ES5中新增的数组方法
array.filter(function(value, index, arr))
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素,主要用于筛选数组
注意它直接返回一个新数组
value: 数组当前项的值
index:数组当前项的索引
arr:数组对象本身
<script>
// filter 筛选数组
var arr = [12, 66, 4, 88, 3, 7];
var newArr = arr.filter(function(value, index) {
// return value >= 20;
return value % 2 === 0;
});
console.log(newArr); // [12,66,4,88]
</script>
如何利用filter()方法进行数组去重?
<script>
//定义一个数组
var arr = [1, 2, 3, 4, 1, 1, 1, 3, 4, 5, 6]
// 分析我们一眼可以看出结果为[1,2,3,4,5,6]
// 使用数组的fliter方法,
// 我们知道回调函数三个形参对应的(数组元素,数组元素的索引,当前数组)
// arr.filter(function(item, index, arr) {
// console.log(item + '---' + index + '---' + arr);
/*通过打印我们得知
1 0 当前数组
2 1 当前数组
3 2 当前数组
4 3 当前数组
1 4 当前数组
1 5 当前数组
1 6 当前数组
3 7 当前数组
. . 当前数组
. . 当前数组
. . 当前数组
. . 当前数组 */
// })
var newArr = arr.filter(function(item, index, arr) {
// return 出的结果是一个数组 filter方法的返回值是一个数组
// indexOf方法的结果是索引 0 1 2 3 会和当前的遍历索引比较
// 如果相等就将结果返回 就会将这一项数组元素放到新数组中
return arr.indexOf(item) === index;
})
console.log(newArr);
</script>

indexOf方法的结果是索引 0 1 2 3 会和当前的遍历索引比较

如果相等就将结果返回 就会将这一项数组元素放到新数组中
本文介绍了ES5中filter()方法的基本用法,展示了如何利用filter进行数组去重,以及如何通过回调函数实现数组筛选。通过实例演示了如何根据值的奇偶性过滤数组和如何利用indexOf判断元素唯一性来达到去重的效果。
2734

被折叠的 条评论
为什么被折叠?



