我是 javascript 新手,这是 Basic Algorithm Scripting 的最后一门课程。我正在尝试理解这行代码,因为我从免费代码营获得前端开发证书的下一部分,我想了解一切。我一直在寻找解决方案并找到了这个。我理解评论中的一些内容,但我很难理解公式,这段代码 100% 有效,但我只需要进一步理解。这是代码:
function rot13(str) {
//retCharArray is an Array of character codes for the solution
var rotCharArray = [];
//regular expression for all upper case letter from A to Z
var regEx = /[A-Z]/;
//split str into a character array
str = str.split("");
for (var x in str) { //iterate over each character in the array
//regEx.test(str[x]) will return (true or false) if it maches the regEx or not
if (regEx.test(str[x])) {
// A more general approach
// possible because of modular arithmetic
// and cyclic nature of rot13 transform
// I DON'T CLEARLY UNDERSTAND THIS CODE BELOW
rotCharArray.push((str[x].charCodeAt() - 65 + 13) % 26 + 65);
} else {
rotCharArray.push(str[x].charCodeAt());
}
}
//make a string with character codes from an array of character codes
str = String.fromCharCode.apply(String, rotCharArray);
return str;
}
// Change the inputs below to test
rot13("SDASasd");