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]