You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript循环内if语句报错:rot13函数else语法异常排查

Fixing Your ROT13 Function: Syntax Error & Logic Issues

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/else structure to remove the rogue code block
  • Corrected the charCodeAt method call syntax
  • Implemented the actual 13-position shift with wrap-around for uppercase letters
  • Used join('') instead of toString() to avoid commas in the final string
  • Switched to let/const instead of var for better scoping (modern JS best practice)

内容的提问来源于stack exchange,提问作者Bobbygllh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:35:15