gpt4 book ai didi

javascript - 凯撒密码(我如何将 for 转换为 .map)

转载 作者:行者123 更新时间:2023-11-29 21:03:04 24 4
gpt4 key购买 nike

这是一个凯撒密码程序,我自己写了这段代码,想把这个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");

最佳答案

下面是使用 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"));

关于javascript - 凯撒密码(我如何将 for 转换为 .map),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45515117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com