Caesar Cipher(如何转换为.map)

时间:2017-08-04 20:37:02

标签: javascript loops for-loop caesar-cipher

这是一个Caesar密码程序,我自己编写了这段代码,并希望将这个for循环转换为.map JavaScript内置函数,我已经尝试了很多次但是无法搞清楚。

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

在这个网站上有很多关于.map的问题,但这对我不起作用。

function rot13(str) {
   var chArray = [];
   str = str.split("");
   
   for(var i in str){
    var char = str[i].charCodeAt(0);
     if(/[A-M]/g.test(str[i])){
       chArray.push(char + 13);
     }
     else if(/[N-Z]/g.test(str[i])){
       chArray.push(char - 13);
     }
     else chArray.push(char);
   }
   str = String.fromCharCode.apply(String,chArray);
  return str;
}

rot13("SERR PBQR PNZC");

4 个答案:

答案 0 :(得分:1)

以下是对代码的简单修改,以使用map(使用变量rotation来避免重复代码):



function rot13(str) {
   str = str.split("");

   var encryptedChArray = str.map(char => {
     var rotation = 0;

     if(/[A-M]/g.test(char)){
       rotation = 13;
     }
     else if(/[N-Z]/g.test(char)) {
       rotation = -13;
     }

     return char.charCodeAt(0) + rotation;
   });

   return String.fromCharCode.apply(String, encryptedChArray);
}

console.log(rot13("SERR PBQR PNZC"));




答案 1 :(得分:1)

您可以将字符串拆分为字符数组,然后在其上进行映射,执行转换,最后将转换后的字符数组连接回字符串。

function rot13(str) {

    // get the char code for the character
    const charCode = str.charCodeAt(0);
    
    if(/[A-M]/g.test(str)){
        return String.fromCharCode(charCode + 13);
    }
    else if(/[N-Z]/g.test(str)){
        return String.fromCharCode(charCode - 13);
    }
    else {
        return String.fromCharCode(charCode);
    }
}

// first split the string into an array of single characters
const newString = "SERR PBQR PNZC".split("").map(rot13).join('');

console.log(newString);

答案 2 :(得分:0)

另一种选择是使用array.map here.

映射方法接受回调,并且该回调将数组中的每个元素作为参数。

示例:

var arr = [1,2,3,4,5];
arr.map(someFunc);

var someFunc = function(currentItem){
     console.log(currentItem);
     //This will output 1
     //2
     //...
}

因此,您可以在传递给map的someFunc中定义cypher转换。

假设您要编码以下字符串

var secretMessage = "hello"
msgArray = secretMessage.split("");

msgArray.map(cypher);

var cypher = function(i){ 
     ///doStuff
}

答案 3 :(得分:0)

如果您想要非常紧凑地执行此操作,您可以执行以下操作:



const A = 'A'.charCodeAt(0)
const M = 'M'.charCodeAt(0)
const N = 'N'.charCodeAt(0)
const Z = 'Z'.charCodeAt(0)
function rot13(str) {
   var chArray = [];
   return String.fromCharCode(...(
     str.split('')
       .map(c => c.charCodeAt(0))
       .map(c =>
         (A <= c && c <= M) ? c + 13 :
         (N <= c && c <= Z) ? c - 13 :
         c
       )
   ))
}

console.log(rot13("SERR PBQR PNZC"))
&#13;
&#13;
&#13;