javascript - 为什么不替换第二个数组 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?"
上面代码中的错误是什么?
解决方案
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?"))
推荐阅读
- regex - 使用 vars 或在 /regex/.test 中重复
- python - 使用“upload_file”在 AWS S3 中上传 csv 在 S3 中获取 0 字节
- javascript - 重新连接后套接字发射不起作用
- firebase - 使用 Firebase 云功能向用户发送通知时未定义的字段
- c# - 在同一控制器的操作中映射到模型和从模型映射
- node.js - 如何使用 docker 中的卷同步 node.js 工作区更改
- asp.net-core - 只在 Scrutor 中直接继承接口的类注册接口
- unity3d - 使用 Vuforia 进行距离测量
- cron - ubunto crontab 重启
- python - 当 DF 发生变化时,如何拥有 DataFrame (pandas) 的子类和自动更新的 Widget (kivy)?