• js 自带的 reduce() 方法


    1.方法说明 , Array的reduce()把一个函数作用在这个Array[x1, x2, x3...]上,这个函数必须接收两个参数,reduce()把结果继续和序列的下一个元素做累积计算,其效果就是:

    [x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)

    2. 使用示例:

     2.1不要使用JavaScript内置的parseInt()函数,利用map和reduce操作实现一个string2int()函数:  

    'use strict';
    
    function string2int(s){
           if(!s){
              alert('the params empty');
               return;
           }
           if(s.length===1){
              return s*1;
           }
           var arr = [];
           for(var i=0; i<s.length; i++){
               arr.push(s.substr(i, 1)*1);
           }
            return arr.reduce(function(x, y){
               return x*10 + y;
            });
    
    }
    // 测试:
    if (string2int('0') === 0 && string2int('12345') === 12345 && string2int('12300') === 12300) {
        if (string2int.toString().indexOf('parseInt') !== -1) {
            alert('请勿使用parseInt()!');
        } else if (string2int.toString().indexOf('Number') !== -1) {
            alert('请勿使用Number()!');
        } else {
            alert('测试通过!');
        }
    }
    else {
        alert('测试失败!');
    }

     2.2 把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']

    'use strict';
    
    function normalize(arr){
       if(!arr){
           alert('the arr is empty!');
           return;
        }
        return arr.map(function(s){
          var temparr = [];
          for(var j=0; j<s.length; j++){
               var str = s.substr(j, 1);
               if(j===0){
                  str = str.toUpperCase();
               }else{
                  str = str.toLowerCase();
               }
               temparr.push(str);
          }
          s = temparr.reduce(function(x, y){
               return x + y;
          });
          return s;
        });
     
    }
    
    // 测试:
    if (normalize(['adam', 'LISA', 'barT']).toString() === ['Adam', 'Lisa', 'Bart'].toString()) {
        alert('测试通过!');
    }
    else {
        alert('测试失败!');
    }
  • 相关阅读:
    手起刀落-一起来写经典的贪吃蛇游戏
    同步、异步、回调执行顺序之经典闭包setTimeout分析
    起步
    设计模式之单例模式与场景实践
    青春是如此美好,又怎忍平凡度过
    nvm管理不同版本的node和npm
    起步
    基础
    调用wx.request接口时需要注意的几个问题
    微信小程序实现各种特效实例
  • 原文地址:https://www.cnblogs.com/rocky-fang/p/5755755.html
Copyright © 2020-2023  润新知