当前位置:   article > 正文

ES6 中filter过滤器的用法_es6数据过滤

es6数据过滤
var sexData=["男","女","女","男","女"];
var filter2=sexData.filter(function(sex){
	return sex==="女"
})

//console.log(filter2)    ["女", "女", "女"]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
//1. 去掉空字符串、undefined、null
var porducts = [
	{name:''},
	{name:"哈哈"}
];
var filter2=porducts.filter(function(item){
	return item.name
})
//console.log(filter2)    
//打印得出  0: {name: "哈哈"}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
//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)
// ["苹果", "香蕉", "芒果"]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/750666
推荐阅读
相关标签
  

闽ICP备14008679号