zoukankan      html  css  js  c++  java
  • 实现javascript中的filter,map,reduce

    先来实现一个遍历Array的forEach函数:

     1 function foreach(array, func) {
     2         for (var i = 0; i < array.length; i++) {
     3                 func(array[i]);
     4         }
     5 }
     6 
     7 function logPrint(element) {
     8     console.log(element);
     9 }
    10 
    11 forEach([2, 5, 7], logPrint);  
    12 //outputs:
    13 //2
    14 //5
    15 //7

    filter:

     1 function filter(func, array) {
     2     var result = [];
     3 
     4     forEach(array, function(element){
     5             if (func(element)) {
     6                 result.push(element);
     7             }
     8     });
     9 
    10     return result;
    11 }
    12 
    13 function gtZero(element) {
    14         if (x > 0) {
    15                 return true;
    16         }
    17 }
    18 
    19 filter(gtZero, [3, -2, 0, 5]);
    20 //[3, 5]

      map:

    function map(func, array) {
            var result = [];
    
            forEach(array, function(element) {
                    result.push(func(element));
            });
    
            return result;
    }
    
    function add1(element) {
      return element+ 1;
    }
    
    map(add1, [0, 2, 4, 6, 8, 10]);
    //[1, 3, 5, 7, 9, 11]

      reduce:

    function reduce(func, init, array) {
             forEach(array, function(element) {
                     init = func(init, element);
             });
     
             return init;
    }
    
    function add(element1, element2) {
      return element1 + element2;
    }
    
    reduce(add, 0, [1, 2, 3, 4]);
    //10

    在ECMAScript5的Array中已经有了Array.prototype.forEach,Array.prototype.filter,Array.prototype.map等方法,

    请参考http://www.ecma-international.org/ecma-262/5.1/#sec-15.4

  • 相关阅读:
    第二部分 设计类型:第8章 方法
    centos7 网卡重命名
    centos7修改主机名
    修改umask值
    mysql表字段属性
    mysql基础操作
    mysql错误代码ERROR 1045 (转载)
    sed高级用法
    shell拷贝原文件到目标对应文件夹
    函数(位置传参)
  • 原文地址:https://www.cnblogs.com/pigzhu/p/3115752.html
Copyright © 2011-2022 走看看