漂亮的代码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);
}
自己写成了一堆屎,好好学习。

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号