Es6常用方法filter
程序员文章站
2022-04-10 15:43:54
1. filter针对数组起过滤作用筛选出符合条件的一个或多个元素 lvar newarr = [ { num: 1, val: 'ceshi', flag: 'aa' }, { num: 2, val: 'ww' } ] console.log(newarr.filter(item => item ......
1. filter针对数组起过滤作用筛选出符合条件的一个或多个元素
lvar newarr = [
{ num: 1, val: 'ceshi', flag: 'aa' },
{ num: 2, val: 'ww' }
]
console.log(newarr.filter(item => item.num===2 ))
// [{num:2,val:'ww'}]
2 .filter 自动多虑数组中 空字符串、undefined、null
var arr = ['1','2',undefined, '3.jpg',undefined]
var newarr = arr.filter(item => item)
console.log(newarr)
var arr = ['1','2',null, '3.jpg',null]
var newarr = arr.filter(item => item)
console.log(newarr)
var arr = ['1','2','', '3.jpg','']
var newarr = arr.filter(item => item)
console.log(newarr)
//["1", "2", "3.jpg"]
3.filter去重功能
var newarr = arr.filter(item => item) console.log(newarr) // ["1", "2", "3.jpg"]
var arr = [1, 2, 2, 3, 4, 5, 5, 6, 7, 7,8,8,0,8,6,3,4,56,2];
var arr2 = arr.filter((x, index,self)=>self.indexof(x)===index)
console.log(arr2); //[1, 2, 3, 4, 5, 6, 7, 8, 0, 56]