如何在JavaScript中统计字符串元音并以数组返回?代码排障求助
Fixing Your Vowel Counting JavaScript Code
Let's break down the issues in your code step by step, then provide a corrected version that works as intended:
Key Issues in the Original Code
- Overwriting the Function Parameter: Your
vowelsfunction accepts a parametera, but immediately reassigns it to"How are you today"—this means any input you pass to the function will be completely ignored. - Incorrect For Loop Condition: The loop uses
i <= a.length, which will run one extra iteration (wheniequalsa.length). Since string indices start at 0, you should usei < a.lengthto avoid trying to access an undefined character. - Broken Condition Checks: Lines like
if (string.charAt(i) == "a" || "A")are invalid. The|| "A"part is always truthy, so this condition will always evaluate to true. You need to explicitly check both cases:a.charAt(i) === "a" || a.charAt(i) === "A". Also, you're referencing a non-existent variablestringinstead of your actual input variablea. - Redundant
varDeclarations: Inside the if blocks, you're usingvar numA += 1;—thevarhere is unnecessary (you already declarednumAat the top) and will throw syntax errors. - Missing Return Statement: Your function creates the
strarray but never returns it, so you can't retrieve the result when calling the function. - Invalid
return(str);in Body: Thereturnstatement in the<body>is outside any function, so it won't execute as intended. You need to call the function and handle its output properly.
Corrected Code
<!DOCTYPE html> <html> <head> <title>Vowel Counter</title> <meta charset="utf-8"> <script> function vowels(inputStr) { // Initialize counters for each vowel (case-insensitive) let numA = 0; let numE = 0; let numI = 0; let numO = 0; let numU = 0; // Loop through each character in the input string for (let i = 0; i < inputStr.length; i++) { const char = inputStr.charAt(i).toLowerCase(); // Convert to lowercase to simplify checks switch(char) { case 'a': numA++; break; case 'e': numE++; break; case 'i': numI++; break; case 'o': numO++; break; case 'u': numU++; break; } } // Return the counts as an array [a, e, i, o, u] return [numA, numE, numI, numO, numU]; } // Example usage: const result = vowels("How are you today"); console.log("Vowel counts:", result); // Logs [2, 2, 0, 2, 1] // To display on the page: document.addEventListener('DOMContentLoaded', function() { document.body.textContent = `Vowel counts (A, E, I, O, U): ${result.join(', ')}`; }); </script> </head> <body> </body> </html>
Additional Improvements
- Used
letinstead ofvarfor block-scoped variables (modern JavaScript best practice). - Converted each character to lowercase with
toLowerCase()to avoid checking both uppercase and lowercase explicitly—this simplifies the code significantly. - Used a
switchstatement instead of multipleifblocks for cleaner, more readable logic. - Added example usage that logs the result to the console and displays it on the page once the DOM is fully loaded.
内容的提问来源于stack exchange,提问作者sa9289
相关产品推荐
相关产品推荐

