• 技术文章 >web前端 >前端问答

    es6中filter过滤器有什么作用

    青灯夜游青灯夜游2023-01-29 14:41:08原创69

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

    本教程操作环境:windows7系统、ECMAScript 6版、Dell G3电脑。

    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)
    // ["苹果", "香蕉", "芒果"]

    【推荐学习:javascript高级教程

    以上就是es6中filter过滤器有什么作用的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:es6数组 ES6
    上一篇:vue文件上传不能大于10mb怎么实现 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • ie6能不能兼容es6• es6是基于哪种语言的语法• es6怎么判断一个变量是否为数组• es6新增运算符有哪些• webpack支持es6吗• es6怎么判断数组里总共有多少项
    1/1

    PHP中文网