我正在做一个凯撒代码练习,很早就遇到了一个问题,这似乎让我感到困惑。如果有任何帮助,我们将不胜感激!这是我的代码:
const caesar = function(str, number) {
let solved = "";
for (let i = 0; i <= str.length; i++) {
let asciiNum = str[i].charCodeAt();
if (asciiNum >- 65 && asciiNum <= 90) {
solved += String.fromCharCode(asciiNum + number);
}
}
};
错误:
Uncaught TypeError: str[i] is undefined
caesar http://127.0.0.1:5501/index.html:102
<anonymous> debugger eval code:1
为什么str[i]未定义?我真的很困惑!
如下重写for循环:
for (let i = 0; i < str.length; i++) {}
它必须是i < str.length
,否则在最后一次迭代中,str[i]将解析为undefined。