javascript - 选择菜单显示未定义不是从数组生成的单词?

标签 javascript html arrays

基本上我有一个应用程序,你可以猜出法语单词的英语单词是什么!由于某种原因,我的选择菜单显示未定义而不是英文单词?我不明白为什么!!

这是我的 jsFiddle,应用程序的精确副本。第一次运行它时,未定义不会显示,但在第二次迭代时它显示 2 个未定义选项??

http://jsfiddle.net/jamesw1/w8p7b6p3/16/

Javascript:

    //James Wainwright's Mobile Apps Assignment
    //Arrays of french and english words.
    var
    RanNumbers = new Array(6),
        foreignWords = ['un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf', 'dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf', 'vingt', 'vingt et un', 'vingt-deux', 'vingt-trois', 'vingt-quatre', 'vingt-cinq', 'vingt-six', 'vingt-sept', 'vingt-huit', 'vingt-neuf', 'trente'],
        translate = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'twenty-one', 'twenty-two', 'twenty-three', 'twenty-four', 'twenty-five', 'twenty-six', 'twenty-seven', 'twenty-eight', 'twenty-nine', 'thirty'],
        number = Math.floor((Math.random() * 30)),
        output = '',
        correctAns = translate[number];

    //Generate random numbers and make sure they aren't the same as each other.
    function wordGen() {
    for (var h = 0; h < RanNumbers.length; h++) {
        var temp = 0;
        do {
            temp = Math.floor(Math.random() * 30);
            while(temp==correctAns){
              temp = Math.floor(Math.random() * 30);
            }
        } while (RanNumbers.indexOf(temp) > -1);
        RanNumbers[h] = temp;

    }
} 

        //Call the previous function
        wordGen();

    //Create dynamic select menu using for loop. This loop runs once (on document load)
    document.getElementById('generatedWord').textContent = foreignWords[number];
    var guess = "<select name='guesses' id='guesses'>";
    for (var i = 0; i < RanNumbers.length; i++) {
            guess += "<option value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
    }
    guess += '<option value="6">' + correctAns + '</option>';
    guess += "</select>";

    //Output the previous.
    document.getElementById('output').innerHTML = guess;
    numGuessed = document.getElementById('guesses').value;

    function arrayValueIndex(arr, val) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] === val) {
                return i;
            }
        }
        return false;
    }

    //Declare variables 'outside' the onclick function so it ensures they work correctly.
    var numGames = 5;
    var numGuesses = 1;
    var correct = 0;
    var wrong = 0;
    var prevNumber;
    var counter = 0;
    var outputted = '';

    //Create arrays that will hold the options they chose, the correct answer for that particular question, and ofcourse the generated word.
    var guessedList = new Array(6);
    var correctList = new Array(6);
    var wordGenerated = new Array(6);

    //On click, Get new word, Calculate how many they got right/wrong, Show the user what they entered, show them the correct values they should've guessed and more...
    document.getElementById('submitAns').onclick = function () {

    //Declare variables for function.
        prevNumber = number;
        number = Math.floor((Math.random() * 30)),
        output = '',
        correctAns = translate[number];
        document.getElementById('numGuess').innerHTML = "Question #" + numGuesses;

    //Check if guess is right or wrong, if right add 1 to correct pile..Visa versa.
         var
        genWord = document.getElementById('generatedWord').textContent,
            select = document.getElementById('guesses'),
            selectedText = select.options[select.selectedIndex].text;
        prevNumber === arrayValueIndex(translate, selectedText) ? correct++ : wrong++;

        //Getting new random numbers that aren't duplicates.
        /*function wordGen() {
            for (var j = 0; j < RanNumbers.length; j++) {
                var temp = 0;
                do {
                    temp = Math.floor(Math.random() * 30);
                } while (RanNumbers.indexOf(temp) > -1);
                RanNumbers[j] = temp;

            }
        }*/

        //Generate a word here. ( call wordGen() ) 
        wordGen();

        //Create dynamic select menu for options they have to choose from.
        document.getElementById('generatedWord').textContent = foreignWords[number];

        //Generate a random number, so that the 'Correct' answer can be randomly put in a position in the select menu. (It won't always be in the same position...It changes depending on the random number
        var correctAnswerIndex = Math.floor(Math.random() * 6);

        //If it's 0...Change it.
        if(correctAnswerIndex == 0)
        {
            correctAnswerIndex++;   
        }

        //Create a select menu of the options...Add the correct answer randomly into the menu.
        var guess = "<select name='guesses' id='guesses'>";
        for (var i = 1; i < RanNumbers.length; i++) {
            //This randomizes where the correct answer will be.
            if(i == correctAnswerIndex)
                 guess += '<option value="'+i+'">' + correctAns + '</option>';
            else
                 guess += "<option selected='selected' value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";

        }
        guess += "</select>";

        //Outputting to the html page.
        document.getElementById('output').innerHTML = guess;
        numGuessed = document.getElementById('guesses').value;

        function arrayValueIndex(arr, val) {
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] === val) {
                    return i;
                }
            }
            return false;
        }
        //Checking of the answers below, Accumilating correct and wrong answer. 
        //Count number of guesses
        numGuesses++;
        //Counter for placing guessed, correct and foreign word into there arrays.
        counter++;

        wordGenerated[counter] = foreignWords[number];
        guessedList[counter] = document.getElementById('guesses').options[select.selectedIndex].text;
        correctList[counter] = translate[number];

       //Once the application has finished...It will produce the following output.
        if (numGuesses == 6) {
            document.getElementById('generatedWord').innerHTML = "<span style='font-size:12px;color:red';>Please click for a new game when ready!</span><br /><p>You got " + wrong + " questions wrong " + "<br />You got " + correct + " questions correct";
                $('#submitAns').hide();
                outputted = "<table>";
                for(var d=1;d<wordGenerated.length;d++){
                    outputted += "<tr><td>Question " + d + ":</td> <td>Generated word: " + wordGenerated[d] + "</td>    <td>Guessed Word: " + guessedList[d] + "</td>   <td>Correct Word: " + correctList[d] + "</td></td>";
                }
                outputted += "</table>";

                //Output it to the html page.
                    document.getElementById('details').innerHTML = outputted;
        }
    };

HTML:

<div data-role="page" id="page">
    <div data-role="header">
        <h1>James' Translation Guessing Game</h1>
    </div>
    <div data-role="content" class="main">  
        <h2 id="display" style="color:rgba(204,51,204,1);">Guess what the generated french word translates to in English!</h2><br />

        <!-- What question we're upto -->
        <h2 id="numGuess">Question #</h2 >

        <!-- The generated French Word  Aswell as end of app details-->
        <div align="center" class="frenchWord" style="position:">

        <!--Generated french word details-->
             <div style="background-color:rgba(51,51,51,0.5);border-radius:4px 10px 2px;"align="center"  id="generatedWord"></div>
             <br />
             <br />
   <!-- Show the user there guessed answers, correct and foreign word -->
             <div id="details"></div>
        </div>

        <!-- Select menu output -->
        <div align="center" id="output"></div>

        <!-- Buttons, Call Functions -->
        <button type="button" style='opacity:0.5' id="submitAns" onClick="translate();">Check</button>
        <input type="button" value="New Game" onClick="document.location.reload(true)">
             <script>
             //Simple animation
             $(document).ready(function(){
                $("#generatedWord").animate({
                    opacity: 0.8,
                    margin: "40px 0px 100px 0px",
                    width: "20%",
                    padding: "30px",
                }, 1500 );
});
</script>
    </div>
    <div data-role="footer">
        <h4>James Wainwright</h4>
    </div>
</div>

最佳答案

我认为你的问题可能出在这个 for 循环中:

该数组声明的长度为 6,因此索引 0-5 可用。当 i = 6 时,您将访问越界索引。通过一些快速测试,将终止条件更改为 i<6 似乎可以解决该问题。

您可能还需要设置 i=0,除非您特别需要访问第二个索引 (i=1)。

//Create a select menu of the options...Add the correct answer randomly into the menu.
    var guess = "<select name='guesses' id='guesses'>";
    for (var i = 1; i <= 6; i++) {
        //This randomizes where the correct answer will be.
        if(i == correctAnswerIndex)
             guess += '<option value="'+i+'">' + correctAns + '</option>';
        else
             guess += "<option selected='selected' value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";

    }

关于javascript - 选择菜单显示未定义不是从数组生成的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26898916/

相关文章:

javascript - 使用 bas64 字符串作为参数调用时, Node gm (imagemagick) 似乎无法使用

javascript - 是否有任何使用工具提示显示验证消息的客户端验证库?

javascript - 如何在 Javascript 中执行非阻塞调用? ( promise 不会那样做。)

javascript - 函数不修改传递的参数值

javascript - 从数据库获取单词并将其传递到在浏览器中运行的脚本文件

php - 正确显示关联数组的结果 Laravel/PHP

javascript - 如何让 style.visibility 与外部样式表一起工作? (仅限 Vanilla javascript,无 jQuery)

HTML:如何从 PRE 标签中删除行间距

html - 我可以选择一个以 "#"开头的 id

Java相当于python数组初始化