求助:str.fromCharCode与newStr.push报‘不是函数’错误排查
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 usingcharCodeAt(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
iintonewStrinstead 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

