1.定义
filter()方法是对原数组进行过滤筛选,产生一个新的数组对象
filter()不会对空数组进行检测(如果对空数组进行筛选,返回值位undefined);
filter()不会改变原始数组;
返回数组包含了符合条件的所有元素,如果没有符合条件的元素则返回空数组;
总结来说:filter是满足条件的留下,是对原数组的过滤,不会对数组进行加工。(这里跟map()的一些区别)
2.语法: array.filter(function(currentValue,index,arr), thisValue)
参数说明 filter方法中的有三个参数。
第一个参数为: 当前正在遍历的元素
第二个参数为: 当前元素索引
第三个参数为: 原数组本身
thisValue: 可选。对象作为该执行回调时使用,传递给函数,用作 “this” 的值。如果省略了 thisValue ,“this” 的值为 “undefined”
一些示例:
1.返回数组array中所有元素都大于等于14的元素
let array = [14, 17, 18, 32, 33, 16, 40];
let brr = array.filter((item) => item > 14);
console.log(brr); // [17, 18, 32, 33, 16, 40]
2.数组去重操作:对数组array中所有相同的元素进行去重复操作
let arr = [1,1,"1","1",true,true,"true",{},{},"{}",null,null,undefined,undefined]
let brr = arr.filter((item, index) => {
console.log(item,index,arr.indexOf(item));
return arr.indexOf(item) === index;
});
console.log(brr);
这里要注意!indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。
如果没有找到匹配的字符串则返回 -1。
注意: indexOf() 方法区分大小写。
在打印台可以看到,每个item、index、以及每个item出现的首次位置,
arr.indexOf(item) === index 所表达的意思就是,只要返回第一次出现的item,从而实现数组去重。(但是对于空对象,无法去重,因为空对象的内存地址不同)
同时这里可以看到,如果判断逻辑比较简单,就不用retrue,直接=>返回。
3.去掉数组中的空字符串(但是空字符串不能包含空格)、undefined、null
let arr = [1,1,"1","1",true,true,"true",'',{},"{}",null,null,undefined,undefined]
let brr = arr.filter(item => item);
console.log(brr);
map()
map()方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组,map()同样不会改变原数组
语法: array.map(function(currentValue,index,arr), thisValue) 参数说明 map方法中的function回调有三个参数
第一个参数为: 当前正在遍历的元素
第二个参数为: 当前元素索引
第三个参数为: 原数组本身
thisValue: 可选。对象作为该执行回调时使用,传递给函数,用作 “this” 的值。如果省略了 thisValue ,“this” 的值为 “undefined”
主要用于处理要返回的数据赋值给新的数组。
例子:
var array1=[1,4,9,16];
const map1 = array1.map(x=>{
if(x == 4){
return x*2;
}
return x;
});
console.log(map1);
其他用法可查看http://t.csdn.cn/G8yYo