JavaScript循环内if语句报错:rot13函数else语法异常排查
Hey there! Let's walk through what's going wrong with your code and get that ROT13 functionality up and running.
First, the Syntax Error Cause
The "unexpected token else" error is happening because your if statement structure is invalid:
// 错误的结构 if (str.charCodeAt(i) > 64 && str.charCodeAt[i] < 91){continue;}{ var cnet = str.charCodeAt(i); yahoo.push(cnet); } else { ... }
After the if block ({continue;}), you added a standalone { ... } code block. JavaScript doesn't recognize this as part of the if statement, so when it hits the else next, it has no matching if to attach to—hence the syntax error.
Also, you made a small method call mistake: str.charCodeAt[i] should be str.charCodeAt(i)—charCodeAt is a string method, not an array, so you need parentheses to invoke it.
Next, Fixing the ROT13 Logic
Your current code doesn't actually implement the ROT13 shift. ROT13 works by shifting each A-Z letter 13 positions forward (wrapping around to the start if you pass Z). Here's the corrected code with proper logic:
function rot13(str) { const result = []; for (let i = 0; i < str.length; i++) { const charCode = str.charCodeAt(i); // Target uppercase letters (ASCII 65 = A, 90 = Z) if (charCode >= 65 && charCode <= 90) { let shiftedCode = charCode + 13; // Wrap around if we go past Z (90) if (shiftedCode > 90) { shiftedCode -= 26; // 26 is total number of letters in the alphabet } result.push(String.fromCharCode(shiftedCode)); } else { // Keep non-uppercase characters (spaces, symbols) as-is result.push(str[i]); } } // Join array into a single string (instead of toString() which adds commas) return result.join(''); } // Test it out! console.log(rot13("SERR PBQR PNZC")); // Outputs: "FREE CODE CAMP"
Key Fixes & Improvements:
- Fixed the
if/elsestructure to remove the rogue code block - Corrected the
charCodeAtmethod call syntax - Implemented the actual 13-position shift with wrap-around for uppercase letters
- Used
join('')instead oftoString()to avoid commas in the final string - Switched to
let/constinstead ofvarfor better scoping (modern JS best practice)
内容的提问来源于stack exchange,提问作者Bobbygllh

