FreeCodeCamp中JavaScript代码报错:无法读取undefined的charAt属性
Fixing the "Can't read property 'charAt' of undefined" Error in Your Title Case Function
Let's walk through what's going wrong and how to fix your JavaScript function step by step.
The Root Cause of the Error
Your code throws that error because of a critical mismatch in your loop logic:
- You split the input string into an array of words (
strArr), but your loop runs for the length of the original string (str.length) instead of the length of the word array (strArr.length). - When the loop index exceeds the number of words in
strArr,strArr[i]becomesundefined, and trying to callcharAt(0)on an undefined value triggers the error.
On top of that, your current code only captures the uppercase first letter of each word—you're missing the rest of the word, which would lead to an incomplete result even if the loop worked.
Corrected Code
Here's the fixed version of your function that works as expected:
function titleCase(str) { var strArr = str.toLowerCase().split(' '); var strUp = []; for(var i = 0; i < strArr.length; i++) { // Combine uppercase first character with the rest of the lowercase word strUp[i] = strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1); } return strUp.join(' '); } titleCase("I'm a little tea pot"); // Returns "I'm A Little Tea Pot"
Key Fixes Explained
- Corrected Loop Condition: Changed
i < str.lengthtoi < strArr.lengthso we only loop through each word in the array, not every character in the original string. - Complete Word Construction: Added
+ strArr[i].slice(1)to append the rest of the lowercase word after the uppercase first character, ensuring full words are preserved. - Proper Array Initialization: Replaced
var strUp = [str.length];withvar strUp = [];to start with an empty array that we fill with modified words (the original initialization created an array with a single element equal to the string length, which was unnecessary).
Alternative Concise Version (Using map)
If you prefer a more modern, concise approach, you can use Array.map() to simplify the code:
function titleCase(str) { return str.toLowerCase().split(' ').map(word => { return word.charAt(0).toUpperCase() + word.slice(1); }).join(' '); }
内容的提问来源于stack exchange,提问作者Ketan Pandey
相关产品推荐
相关产品推荐

