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

求助:str.fromCharCode与newStr.push报‘不是函数’错误排查

Fixing Your Rot13 Function Errors

Let's walk through what's going wrong with your rot13 code and fix those errors step by step:

First Error: str.fromCharCode is not a function

The fromCharCode method is a static method of the String constructor, not a method you can call on a string instance (like your str variable). Instead of str.fromCharCode(), you need to use String.fromCharCode() — this function takes ASCII code values and returns the corresponding characters.

Second Error: newStr.push is not a function

You initialized newStr as var newStr = str, which makes it a string. But push() is a method exclusive to arrays, not strings. To fix this, you should start with an empty array for newStr, push your processed characters into it, then convert it back to a string when returning the result.

Additional Logic Issues in Your Code

Beyond the two errors, your rot13 logic had a few gaps:

  • You tried to subtract 13 directly from str[i] (a character), but you need to first get its ASCII code using charCodeAt(i).
  • Rot13 is a cyclic cipher — if subtracting 13 takes you below the ASCII value of 'A' (65), you need to add 26 to wrap back around to the end of the uppercase alphabet.
  • You were pushing the loop index i into newStr instead of the processed character.

Corrected Rot13 Function

Here's the fixed code with explanations:

function rot13(str) {
  let newStr = []; // Start with empty array to collect processed characters
  for (let i = 0; i < str.length; i++) {
    const charCode = str.charCodeAt(i);
    // Only process uppercase letters (ASCII 65-90)
    if (charCode >= 65 && charCode <= 90) {
      let newCharCode = charCode - 13;
      // Wrap around if we go below 'A'
      if (newCharCode < 65) {
        newCharCode += 26;
      }
      newStr.push(String.fromCharCode(newCharCode));
    } else {
      // Leave non-uppercase characters (spaces, punctuation) unchanged
      newStr.push(str[i]);
    }
  }
  // Convert array back to string before returning
  return newStr.join('');
}

// Test the function
console.log(rot13("SERR PBQR PNZC")); // Outputs: "FREE CODE CAMP"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:46:17