You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组操作技术问题:如何从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 entire tabLetters array, 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_name are declared without let/var, making them global and prone to bugs.
  • No result output: You're not sending the final matched text to the result input 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

  • indexOf for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:27:07