作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是一个凯撒密码程序,我自己写了这段代码,想把这个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/
我刚刚开始学习 C 语言类(class),并且遇到了命令行参数的问题。分配是这样的(还有更多,但这是开头有关命令行参数的部分): - 你的程序必须接受一个命令行参数,一个非负整数。 - 如果您的程序在
我需要检查命令行参数中是否有非数字字符。例如: ./problem 20x 应该打印出“不是数字”,因为它包含一个 x。我的代码似乎没有循环遍历命令行参数中的所有字符。 我基本上尝试了不同类型的循环,
这里我有从标准输入将字符流输入到数组中的代码。然后将该数组转换为二维数组。然后,它将该数组从行列顺序更改为列行顺序。然后它打印出创建凯撒移位加密的新数组。我遇到的问题是我的数组开始使用第二个用户输入的
我有点被这个问题困住了。当我运行程序时,由于某种原因,循环经过 z 的所有字母都不会打印。问题来自这个链接:http://docs.cs50.net/2016/x/ap/problems/caesar
我是一名优秀的程序员,十分优秀!