filter()
概念
1、方法会创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
2、方法不会改变原始数组。
const arr = [
{ id: 11, name: "lin", parent: 1 },
{ id: 21, name: "chen", parent: 2 },
{ id: 31, name: "wei", parent: 3 },
{ id: 12, name: "hui", parent: 1 },
{ id: 13, name: "dong", parent: 1 },
]
const newArr = arr.filter(item => item.parent == 1)
console.log(newArr)
打印结果
[
{ id: 11, name: "lin", parent: 1 },
{ id: 12, name: "hui", parent: 1 },
{ id: 13, name: "dong", parent: 1 },
]
return后面判断结果,取布尔值,true的话就把该元素添入新的filter数组中,false的话,不会添进filter的数组中。
使用
1.去除数组中不符合的元素
const arr = ["as", "ab" ,"ac" ,"bc", "sd"]
const newArr = arr.filter(item => item.indexOf('a') > -1) // 包含‘a’
const newBrr = arr.filter(item => item.indexOf('a') < 0) // 不包含‘a’
console.log(newArr, newBrr) ["as", "ab" ,"ac"] ["bc", "sd"]