赞
踩
var sexData=["男","女","女","男","女"];
var filter2=sexData.filter(function(sex){
return sex==="女"
})
//console.log(filter2) ["女", "女", "女"]
var porducts = [
{name: 'apple',type: 'red'} ,
{name: 'orange',type: 'orange'},
{name: 'banana',type: 'yellow'},
{name: 'mango',type: 'yellow'}
];
var filter2=porducts.filter(function(item){
return item.type==='yellow'
})
//console.log(filter2)
//0: {name: "banana", type: "yellow"}1: {name: "mango", type: "yellow"}
1. filter()
返回符合条件的元素的数组[]
筛选回调函数,有三个参数
语法:
array.filter((value, index, arr) => {value === '匹配对象'})
特殊用法:
1. 去掉空字符串、undefined、null
array.filter((value, index, arr) => {value})
2. 数组去重
array.filter((value, index, arr) => {arr.indexOf(value) === index})
//1. 去掉空字符串、undefined、null
var porducts = [
{name:''},
{name:"哈哈"}
];
var filter2=porducts.filter(function(item){
return item.name
})
//console.log(filter2)
//打印得出 0: {name: "哈哈"}
//2. 数组去重
array.filter((value, index, arr) => {arr.indexOf(value) === index})
var porducts = ['苹果','香蕉','苹果','芒果']
var filter2=porducts.filter(function(item,index,porducts){
return porducts.indexOf(item)==index
})
//console.log(filter2)
// ["苹果", "香蕉", "芒果"]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。