zoukankan      html  css  js  c++  java
  • 漂亮的代码5:数组与字符一样的操作

    看到这题:

    
    // 依次替换第一个参数中的字符串,用第二个参数。
    var str = "TRaduttore"
    
    str.tr( "auioe", "4-103" )  // -> "TR4d-tt0r3"
    str.tr( "aeiouR", ["A","E","I","O","U","r"] )  // -> "TrAdUttOrE"
    
    var hi = "Hello Happy CodeWarriors"
    
    hi.tr( ["ello","Happy","Wa","ior"],["ola","Felices","Gue","ero"]) // -> "Hola Felices CodeGuerreros"
    hi.tr( ["ll","pp","rr"], "LPR" )  // -> "HeLo HaPy CodeWaRiors"
    
    

    这是我解决的方案:

    String.prototype.tr1 = function(fromList, toList) {
        fromList = fromList || [];
        toList = toList || [];
    
        var pairs = {};
    
        var a = Array.isArray(fromList) ? fromList : fromList.split("");
        var b = Array.isArray(toList) ? toList : toList.split("");
    
        a.forEach((x, i) => pairs[x] = b[i]);
    
        return a.reduce((acc, cur) => acc.replace(new RegExp(cur, "g"), function(x) {
            return pairs[x] + "" || ""; // 这里如果 toList 中包括 0 的话就不行,所以加上一个空字符转成字符,在这里卡了很久。
        }), this);
    
    }
    
    

    看别人的解决方案:

    String.prototype.tr = function(from, to) {
        for (var s = this, i = 0; i < from.length; i++) {
            s = s.split(from[i]).join(to ? to[i] : '');
        }
    
        return s;
    }
    
    // 我自己改进一下
    String.prototype.tr = function(from, to) {
        return (Array.isArray(from) ? from : from.split("")).reduce((acc, cur, i) => acc.split(cur).join(to ? to[i] : ''), this);
    }
    
    

    自己写成了一堆屎,好好学习。

  • 相关阅读:
    集算器如何优化SQL计算(2)分组
    集算器如何优化SQL计算(1)动态列
    android DOM解析Xml
    ASP.NET 抓取网页内容
    抓取HTML网页数据
    [转]Android的网络与通信
    Android的三种网络通信方式
    Android通过onDraw实现在View中绘图操作
    Android Canvas类介绍
    DatabaseMetaData的用法(转)
  • 原文地址:https://www.cnblogs.com/htoooth/p/5546646.html
Copyright © 2011-2022 走看看