我编写了一个函数,其中接收到的字符串中的字母值移动了13个位置。
我的解决方案非常低效,如果更改了班次因素,则需要完全重写。
这是我的解决方案:
function rot13(str) {
var charArray = str.split("");
var myArray = [];
for (var i = 0; i < charArray.length; i++) {
switch (charArray[i]) {
case "A":
myArray.push("N");
break;
case "B":
myArray.push("O");
break;
case "C":
myArray.push("P");
break;
case "D":
myArray.push("Q");
break;
case "E":
myArray.push("R");
break;
case "F":
myArray.push("S");
break;
case "G":
myArray.push("T");
break;
case "H":
myArray.push("U");
break;
case "I":
myArray.push("V");
break;
case "J":
myArray.push("W");
break;
case "K":
myArray.push("X");
break;
case "L":
myArray.push("Y");
break;
case "M":
myArray.push("Z");
break;
case "N":
myArray.push("A");
break;
case "O":
myArray.push("B");
break;
case "P":
myArray.push("C");
break;
case "Q":
myArray.push("D");
break;
case "R":
myArray.push("E");
break;
case "S":
myArray.push("F");
break;
case "T":
myArray.push("G");
break;
case "U":
myArray.push("H");
break;
case "V":
myArray.push("I");
break;
case "W":
myArray.push("J");
break;
case "X":
myArray.push("K");
break;
case "Y":
myArray.push("L");
break;
case "Z":
myArray.push("M");
break;
case " ":
myArray.push(" ");
break;
case ",":
myArray.push(",");
break;
case "!":
myArray.push("!");
break;
case "?":
myArray.push("?");
break;
case ".":
myArray.push(".");
break;
}
}
console.log(myArray.join(""));
}
rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.");
&#13;
你能告诉我一个更有效,更简单的解决方案吗?
答案 0 :(得分:2)
这是一种可能的实现,能够传递任何(正)旋转值和其他替换表。写于ES6。
function rotn(str, rotation = 13, map = {}) {
const table = {}; // New table, to avoid mutating the parameter passed in
// Establish mappings for the characters passed in initially
for (var key in map) {
table[map[key]] = key;
table[key] = map[key];
}
// Then build the rotation map.
// 65 and 97 are the character codes for A and a, respectively.
for (var i = 0; i < 26; i++) {
table[String.fromCharCode(65 + i)] = String.fromCharCode(65 + (i + rotation) % 26);
table[String.fromCharCode(97 + i)] = String.fromCharCode(97 + (i + rotation) % 26);
}
return str.split('').map((c) => table[c] || c).join('');
}
console.log(rotn("Gur dhvpx oebja Qbt whzcrq bire gur ynml Sbk.", 13, {'.': '!'}));
答案 1 :(得分:1)
以下是使用reduce函数的示例:
function rot13(str) {
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return str.split("").reduce(function(a, b) {
if (chars.indexOf(b) == -1) {
return a + b;
}
return a + chars[(chars.indexOf(b)+13) % chars.length]
}, "");
}
console.log(rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK."));