Open zilongxuan001 opened 6 years ago
20180402参考Jason Luboff
代码
function rot13(str) { // LBH QVQ VG!
var convertArray= str.split("");
var newArray = [];
for(i=0;i<convertArray.length;i++){
newArray.push(convertArray[i].charCodeAt());
if (newArray[i]>=65 && newArray[i]<=77){
newArray[i] +=13;
} else if(newArray[i]>=78){
newArray[i]=(newArray[i]+12)-25;
}
}
var finalString=String.fromCharCode.apply(null,newArray);
return finalString;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
Jason Luboff使用了fromCharCode.apply()
方法。直接将数组变成字符串。
来源:https://jsperf.com/string-fromcharcode-apply-vs-string-fromcharcode-using-
65
代表A
,77
代表M
,90
代表Z
。
一直纠结于标点符号如.
和!
,以及空格怎么转换,其实多此一举,因为if else
限制了ASCII里大写字母的范围,标点符号和空格在范围之外,无需转换。
挑战
凯撒密码,大写数字前移13位,为密码,求解码。
代码
结果显示
帮助
String.prototype.charCodeAt() String.fromCharCode()
来源
https://www.freecodecamp.org/challenges/caesars-cipher