首页 > 解决方案 > 为什么不替换第二个数组 last13 中的所有字母?

问题描述

我的问题是只替换last13数组中的第一个字符。

var last13我想替换所有字符first13

 var first13 = first13Letter.map(x=>x).join(',');

 var last13 = last13Letter.map(y=>y).join(',');

我的代码

function rot13(str) {

  var first13Letter = ["A","B","C","D","E","F","G","H","I","J","K","L","M"];

  var last13Letter = ["N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

  var first13 = first13Letter.map(x=>x).join(',');

  var last13 = last13Letter.map(y=>y).join(',');


  for(let i=0; i<first13.length; i++){

     if(str.indexOf(first13[i]) !== -1){
        str = str.replace(first13[i],last13[i])
     }else{
        str = str.replace(last13[i],first13[i]) // i want to replace all letter from last13 to first13 letter but this replace only first letter.
     }
  }  
  return str;
}

console.log(rot13("SERR YBIR?"))


//output:"FRRR LOVR?"
//expect output: "FREE LOVE?"

上面代码中的错误是什么?

标签: javascriptstringreplace

解决方案


function rot13(str) {
    const first13Letter = ["A","B","C","D","E","F","G","H","I","J","K","L","M"];
    const last13Letter = ["N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
    return str.split('')
              .map(s => last13Letter.indexOf(s) >= 0 ? first13Letter[last13Letter.indexOf(s)] : 
                        first13Letter.indexOf(s) >= 0 ? last13Letter[first13Letter.indexOf(s)] : s)
              .join('')
}
console.log(rot13("SERR YBIR?"))


推荐阅读