1.創(chuàng)建一個(gè)數(shù)組壶谒,判斷數(shù)組中是否存在某個(gè)值
var newarr = [
{ num: 1, val: 'ceshi', flag: 'aa' },
{ num: 2, val: 'ceshi2', flag: 'aa2' }
]
console.log(newarr.filter(item => item.num===2 ))
//答案 0: {num: 2, val: "ceshi2", flag: "aa2"}
2.去掉空數(shù)組空字符串膘壶、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)
3.去掉數(shù)組中不符合項(xiàng)
var arr = [20,30,50, 96,50]
var newArr = arr.filter(item => item>40)
console.log(newArr)
4.過濾不符合項(xiàng)
var arr = ['10','12','23','44','42']
var newArr = arr.filter(item => item.indexOf('2')<0)
console.log(newArr)
5.數(shù)組去重
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]
數(shù)組去重方法二: 用set 去重:
let arr = [1,2,2,3,4,5,5,6];
let newArr =Array.from(new Set(arr))
console.log(newArr) // [1号醉,2画饥,3玩荠,4漆腌,5,6]
6 filter回調(diào)函數(shù)
var arr = ['A', 'B', 'C'];
var r = arr.filter(function (element, index, self) {
console.log(element); // 依次打印'A', 'B', 'C'
console.log(index); // 依次打印0, 1, 2
console.log(self); // self就是變量arr
return true;
});