实现字符串大小写互换功能及JavaScript代码问题修正
Fixing JavaScript String Case Swap Code
Let's walk through fixing this code to properly swap lowercase and uppercase letters in the string. First, let's break down the issues in the original code:
isLetterfunction returns wrong type: It should return a boolean (true/false) instead of the letter or-1—we just need to know if the character is a letter, not return the character itself.- Loop condition error:
i <= message.lengthwill cause an out-of-bounds error since string indices start at 0 and go up tomessage.length - 1. It should bei < message.length. - Incorrect argument to
isLetter: You're passing the indexiinstead of the actual charactermessage[i]. - Invalid character check:
message[i].toLowerCase()is a string (truthy), so the condition will always pass. We need to compare the original character to its lowercase/uppercase version to check its case. - Strings are immutable in JavaScript: You can't directly modify
message[i]—we need to build a new string with the swapped characters. - Typos and incomplete code:
toLowerCas...is missing an 'e', and the else-if block isn't finished.
Here's the corrected, working code:
let message = "heY, WHAt are you dOING?"; let count_changes = 0; let newMessage = ""; // We'll build the swapped string here // Updated isLetter to return boolean let isLetter = (letter) => { return ('a' <= letter && letter <= 'z') || ('A' <= letter && letter <= 'Z'); } for(let i = 0; i < message.length; i++) { const char = message[i]; if (isLetter(char)) { if (char === char.toLowerCase()) { // Character is lowercase, convert to uppercase newMessage += char.toUpperCase(); count_changes++; } else if (char === char.toUpperCase()) { // Character is uppercase, convert to lowercase newMessage += char.toLowerCase(); count_changes++; } } else { // Not a letter, add it as-is newMessage += char; } } console.log(newMessage); // Output: "HEy, whAT ARE YOU Doing?" console.log(`Number of case changes: ${count_changes}`);
Key Fixes Explained:
isLetterfunction: Now returnstrueif the input is a letter,falseotherwise—this makes the condition checks cleaner.- New string
newMessage: Since we can't modify the original string directly, we append each processed character to this new string. - Proper case checks: We compare the original character to its lowercase/uppercase equivalent to determine its current case, then convert it accordingly.
- Fixed loop bounds:
i < message.lengthensures we only iterate over valid characters in the string. - Handled non-letter characters: Any character that isn't a letter is added to
newMessagewithout changes, preserving punctuation and spaces.
内容的提问来源于stack exchange,提问作者user6311492
相关产品推荐
相关产品推荐

