zoukankan      html  css  js  c++  java
  • map与filter的区别

    原生js中数组可以直接通过map(),filter()函数来进行一次操作,他们分别是做一次统一映射,和一次过滤。说的更通俗一点,就是map函数之后,数组元素个数不变,但是按照一定的条件转换,数组元素发生了变化。filter函数之后,数组元素个数可能发生了改变,但是数组元素不会发生改变。

    下面通过示例说明一下这两个方法的用法。

    map(function(item,index){
           return func(item);

    });

    filter(function(item,index){
          return func(item);

    }):

    示例中,给定一个数组,var arr = ["abc","aaa","bcd"],通过map函数,我们将他们转大写,然后通过filter函数,将A开头的留下。

    $(function(){        
        var arr = ["abc","aaa","bcd"];
        console.log(arr);
        arr = arr.map(function(item,index){
           console.log(item,index);
           return String.prototype.toUpperCase.call(item);
        });
        console.log(arr);
        arr = arr.filter(function(item,index){
            console.log(item,index);
            return String.prototype.startsWith.call(item,"A");
        });
        console.log(arr);
    });

    运行结果,如下:

    map,filter函数均有两个参数item,index 分别是数组元素的值和索引,我们一般对item进行转换。

    另外,jQuery也提供了map,filter方法,用法和原生的map,filter类似,只不过index,item参数位置和原生正好相反。

    $(function(){        
        var arr = ["abc","aaa","bcd"];
        arr = $(arr).map(function(index,item){
            console.log(index,item);
            return String.prototype.toUpperCase.call(item);
        }).filter(function(index,item){
            console.log(index,item);
            return String.prototype.startsWith.call(item,"A");
        });
        console.log(arr);
        arr = $.makeArray(arr);
        console.log(arr);
    });

    运行结果如下:

      

    map,filter方法都会对数组所有元素进行一次转换。

  • 相关阅读:
    npm run build无法打包的可能原因 npm ERR! missing script: build
    java的Scanner类的close()方法引来的故事
    Markdown语法1
    MarkdownPad2破解安装&使用
    MarkDown语法5
    Markdown语法2
    Markdown0
    Sublime Text配置anaconda环境
    解决:Tensorflowgpu中的Could not load dynamic library ‘cudart64_101.dll‘; dlerror: cudart64_101.dll not found
    Markdown语法4
  • 原文地址:https://www.cnblogs.com/yu19991126/p/14867322.html
Copyright © 2011-2022 走看看