1.创建一个数组,判断数组中是否存在某个值
var arr = [
{ name:'xdd', age:50},
{ name: 'xm', age: 12 }
]
var newArr = arr.filter(item => item.name=='xdd' )
// newArr : [{name:'xdd', age:50}]
2.去除 ‘’ ,undefined,null, 0
var arr = ['1',2,undefined, 'xdd',undefined,'0', 0, null, []]
var newArr = arr.filter(item => item)
// newArr : ['1','2','xdd', '0', []]
3.去掉数组中不符合项
var arr = [1, 2, 3, 4, 5,4, 6]
var newArr = arr.filter(item => item>4)
// newArr : [5, 6]
4.数组去重
var arr = [1, 2, 6, 3, 4, 5,4, 6,4,5,6,1,5,5,6,2]
var newArr = arr.filter((x, index, self)=>{
// x : 数组每一项的值
// index: 每一项的下标
// self: 当前数组
return self.indexOf(x)===index
})
// newArr: [1,2,6,3,4,5]
网友评论