数组操作技术问题:如何从tabName数组中获取对应索引?
Fixing the Array Index Matching Issue for Your Name Generator
Hey julliiie! Let's get your name generator working properly. Your current code has a few key issues preventing it from fetching the right array indexes—let's break them down and fix them step by step.
What's Wrong with the Original Code?
- Incorrect while loop condition: You're comparing a single character (
first_name_character) to the entiretabLettersarray, which will never be true. You need to check against individual elements in the array. - Missing lastName handling: The requirement calls for using both first and last name initials, but your code only touches the first name.
- Unscoped variables: Variables like
first_nameare declared withoutlet/var, making them global and prone to bugs. - No result output: You're not sending the final matched text to the
resultinput field. - Case sensitivity: If the user enters a capitalized initial (like "A"), it won't match the lowercase letters in
tabLetters. - Invalid HTML structure: Your
<body>tag is nested inside<head>, which is invalid and can cause unexpected behavior.
Fixed Code with Explanations
Here's the corrected version that meets all your requirements:
<!DOCTYPE html> <html> <head> <script type="text/javascript"> // Declare arrays (using const since they won't change) const tabName = ['Chaton', 'Aigle', 'Bison', 'Blaireau']; const tabAdjective = ['PETEUR', 'BIGLEUX', 'CRETIN', 'MALIN']; const tabLetters = ['a','b','c','d']; function main() { // Get input values and convert to lowercase to avoid case issues const firstName = document.getElementById('save_first_name').value.toLowerCase(); const lastName = document.getElementById('save_name').value.toLowerCase(); // Extract the first character of each name const firstInitial = firstName.charAt(0); const lastInitial = lastName.charAt(0); // Find the index of each initial in tabLetters (returns -1 if not found) const nameIndex = tabLetters.indexOf(firstInitial); const adjIndex = tabLetters.indexOf(lastInitial); // Handle cases where initial isn't in a-d (fallback to "Unknown") const selectedName = nameIndex !== -1 ? tabName[nameIndex] : 'Unknown'; // Convert adjective to title case (matches your example: "Bigleux" instead of "BIGLEUX") const selectedAdj = adjIndex !== -1 ? tabAdjective[adjIndex].charAt(0) + tabAdjective[adjIndex].slice(1).toLowerCase() : 'Unknown'; // Combine results and set to the result input document.getElementById('result').value = `${selectedName} ${selectedAdj}`; } </script> </head> <body> <center> <h2>Exercice 01</h2> First Name : <input type="text" id="save_first_name" size="15"> Name : <input type="text" id="save_name" size="15"> <input type="button" value="ok" onclick="main()"> <input type="text" id="result" size="25" readonly> </center> </body> </html>
Key Improvements Explained
indexOffor easy index lookup: Instead of a buggy while loop,tabLetters.indexOf(initial)directly gives us the position of the initial in the array—cleaner and more reliable.- Case insensitivity: By converting input values to lowercase, we ensure matches regardless of how the user types their name (e.g., "Amelia" or "amelia" both work).
- Error handling: If the user enters an initial outside a-d, we show "Unknown" instead of breaking the code.
- Title case for adjectives: The code converts all-uppercase adjectives to title case (like "Bigleux") to match your example output.
- Valid HTML structure: Fixed the nested
<head>/<body>issue and changed the submit button to a regular button (since we're not submitting a form). - Scoped variables: Used
const(since values don't change) to keep variables local to the function and avoid global pollution.
Testing with your example: entering "amelia" (first name) and "bael" (last name) will output Chaton Bigleux exactly as expected!
内容的提问来源于stack exchange,提问作者julliiie
相关产品推荐
相关产品推荐

