我尝试在 JavaScript 中构建 ROT 13 密码,我做到了但输出未显示在控制台中请检查其中有什么问题

I try to build ROT 13 cipher in JavaScript, I did it but output not shown in console please check what's wrong in it

一种常见的现代用法是 ROT13 密码,其中字母的值移动 13 位。因此 'A' ↔ 'N'、'B' ↔ 'O',依此类推。

function rot13(str) {
    let newStr="";
  let upperAlph=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","W","X","Y","Z"]
  let rotAlph=["N","O","P","Q","R","S","T","U","V","W","X","Y","Z","A","B","C","D","E","F","G","H","I","J","K","L","M"];
  for(let i=0; i<str.length; i++){
 
    let letter=str[i];
    let letTest=/[A-Z]/g;
    if(letTest.test(letter)){
      let indexOfLetter=upperAlph.indexOf(letter);
      let newLetter=rotAlph[indexOfLetter];
      newStr+newLetter;
    }
    else{
      newStr+letter;
    }
  }
  return newStr;
}

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

已修复您的代码,请查看第 12 行和第 15 行,我相信:

function rot13(str) {
    let newStr="";
  let upperAlph=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","W","X","Y","Z"]
  let rotAlph=["N","O","P","Q","R","S","T","U","V","W","X","Y","Z","A","B","C","D","E","F","G","H","I","J","K","L","M"];
  for(let i=0; i<str.length; i++){
 
    let letter=str[i];
    let letTest=/[A-Z]/g;
    if(letTest.test(letter)){
      let indexOfLetter=upperAlph.indexOf(letter);
      let newLetter=rotAlph[indexOfLetter];
      newStr += newLetter;
    }
    else{
      newStr += letter;
    }
  }
  return newStr;
}

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

我也会使用地图类型对象而不是 2 个数组:

alphMap = {A: 'N', B: 'O', C: 'P', ..., Z: 'M'};

您可以像这样找到您的替代字母:

let newLetter = alphMap[letter];

无需匹配索引。

你错过了 upperAlph 的 U 和 V

    function rot13(str) {
    let newStr="";
    let upperAlph=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
  let rotAlph=["N","O","P","Q","R","S","T","U","V","W","X","Y","Z","A","B","C","D","E","F","G","H","I","J","K","L","M"];
  for(let i=0; i<str.length; i++){
 
    let letter=str[i];
    let letTest=/[A-Z]/g;
    if(letTest.test(letter)){
      let indexOfLetter=upperAlph.indexOf(letter);
      let newLetter=rotAlph[indexOfLetter];
      newStr += newLetter;
    }
    else{
      newStr += letter;
    }
  }
  return newStr;
}