es6中filter过滤器怎么使用

发布时间:2023-01-30 14:26:58 作者:iii
来源:亿速云 阅读:135

这篇“es6中filter过滤器怎么使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“es6中filter过滤器怎么使用”文章吧。

在es6中,filter过滤器对数组元素进行过滤并返回一个新的数组。filter()函数会创建一个新数组,其包含通过所提供回调函数实现的测试的所有元素,语法“arr.filter(callback(element[, index[, array]])[, thisArg])”;如果没有任何数组元素通过测试,则返回空数组。

ES6中的filter过滤器

filter函数俗称过滤器,函数作用:对数组元素进行过滤并返回一个新的数组;

filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。

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"}

语法

var newArray = arr.filter(
  callback(element[, index[, array]])[, thisArg]
)

参数

返回值

描述

特殊用法:

  1. 去掉空字符串、undefined、null

array.filter((value, index, arr) => {value})

  2. 数组去重

array.filter((value, index, arr) => {arr.indexOf(value) === index})

例子

1、过滤 JSON 中的无效条目

以下示例使用 filter() 创建具有非零 id 的元素的 json。

var arr = [
  { id: 15 },
  { id: -1 },
  { id: 0 },
  { id: 3 },
  { id: 12.2 },
  { },
  { id: null },
  { id: NaN },
  { id: 'undefined' }];var invalidEntries = 0;function isNumber(obj) {
  return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);}function filterByID(item) {
  if (isNumber(item.id) && item.id !== 0) {
    return true;
  } 
  invalidEntries++;
  return false; }var arrByID = arr.filter(filterByID);console.log('Filtered Array\n', arrByID); // Filtered Array// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]console.log('Number of Invalid Entries = ', invalidEntries); // Number of Invalid Entries = 5

2、去掉空字符串、undefined、null

//2. 去掉空字符串、undefined、null
var porducts = [
	{name:''},
	{name:"哈哈"}
];
var filter2=porducts.filter(function(item){
	return item.name
})
//console.log(filter2)    
//打印得出  0: {name: "哈哈"}

3、数组去重

//3. 数组去重
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)
// ["苹果", "香蕉", "芒果"]

以上就是关于“es6中filter过滤器怎么使用”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

推荐阅读:
  1. ES6 Promise异步操作的状态有哪些
  2. ES6的Generator函数执行机制是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

es6 filter

上一篇:vue如何实现文件上传不能大于10mb

下一篇:vue实现tab的方式有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》