ES6 map与filter
ES6 map与filter
1、map
let arr1 = [1,2,3]; let arr2 = arr1.map((value,key,arr) => { console.log(value) // 1,2,3 console.log(key) // 0,1,2 console.log(arr) //[1,2,3] [1,2,3] [1,2,3] return value * value; }) console.log(arr1); // [ 1, 2, 3 ] console.log(arr2); // [ 1, 4, 9 ]
2、filter
filter 过滤函数,返回符合条件的元素数组。
let arr1 = [1,2,3]; let arr2 = arr1.filter((value,key,arr) => { console.log(value) // 1,2,3 console.log(key) // 0,1,2 console.log(arr) // [1,2,3] return value >= 3 ? false : true; //内部走的就是value>=3 成立吗,成立的部分返回,不成立的部分不返回。 }) console.log(arr1); // [ 1, 2, 3 ] console.log(arr2); // [ 1, 2 ]
- 筛选符合条件项
//返回数组中大于等于 2的新数组 console.log("--------------筛选出(大于等于2的)-----------------------") let arr = [1, 2, 3] let newArr = arr.filter(item => item >= 2) console.log(newArr)
- 数组去重
let arr5 = [1, 2, 2, 3, 4, 5, 5, 6]; let newArr4 = arr5.filter((x, index, self) => { return self.indexOf(x) === index }) console.log(newArr4) //[1,2,3,4,5,6]
- 去掉空字符串、undefined、null
//filter() 去掉空字符串、undefined、null let arr4 = ['', '1', '2', undefined, '3.jpg', undefined] let newArr3 = arr4.filter(item => item) console.log(newArr3); //['1', '2', '3.jpg']
- 筛选数组对象
let arr = [ {a:'苹果',b:'面包',c:'吃'}, {a:'香蕉',b:'面包',c:'不吃'}, {a:'香蕉',b:'苹果',c:'吃'}, {a:'苹果',b:'香蕉',c:'不吃'}, ] let newarr8 = arr7.filter((value, index, arr) => { return value.a != '苹果' }) console.log(newarr8) //[{a:'香蕉',b:'面包',c:'不吃'},{a:'香蕉',b:'苹果',c:'吃'}]
let a = '苹果'; //筛选参数a let b = '面包'; //筛选参数b let c = '' //筛选参数c let arr = [ {a:'苹果',b:'面包',c:'吃'}, {a:'香蕉',b:'面包',c:'不吃'}, {a:'香蕉',b:'苹果',c:'吃'}, {a:'苹果',b:'香蕉',c:'不吃'}, ]; if (a != '') { arr = arr.filter(item => item.a === a) } if (b != '') { arr = arr.filter(item => item.b === b) } if (c != '') { arr = arr.filter(item => item.c === c) } console.log(arr) // 筛选结果: [{a:'苹果',b:'面包',c:'吃'}]
让每一天过的有意义!