【问题标题】:Check if array element exist if not skip to next with JavaScript如果不使用 JavaScript 跳到下一个,则检查数组元素是否存在
【发布时间】:2014-09-01 08:28:14
【问题描述】:

我正在尝试从一组答案中获取 3 个随机答案并将它们存储到一个新数组中。 因此,selectedAnswers 的新数组几乎将有 3 个来自答案池的随机答案,以及正确的答案。我想我知道了,但唯一的问题是,如果已经使用了数组元素,我不知道如何让它跳过,而是添加一个不同的元素。所以我最终在我的新数组中有重复。

在此处查看代码。

http://jsfiddle.net/oybojgzm/2/

var answerList = ["answer 1", "answer 2", "answer 3", "answer 4", "answer 5"];
var correctAnswer = "CORRECT!";
var selectedAnswers = [correctAnswer];
var randomNumber = 0;

function randomAnswer() {
    if (selectedAnswers.length < 4) {
        randomNumber = Math.floor((Math.random() * answerList.length) +
            1) - 1;

        for (i = 0; i < answerList.length; i++) {
            if (answerList[randomNumber] === answerList[i]) {
                randomNumber = Math.floor((Math.random() * answerList.length) +
            1) - 1;

                randomAnswer();

            } else {
                selectedAnswers.push(answerList[i]);
                console.log(selectedAnswers);
                randomNumber = Math.floor((Math.random() * answerList.length) +
            1) - 1;
                randomAnswer();
                break;
            }
        }
    }
}




randomAnswer();

【问题讨论】:

  • 使用selectedAnswers.indexOf(answerList[randomNumber])查看答案是否已经在数组中。

标签: javascript arrays


【解决方案1】:

我建议使用 shuffle 函数,而不是多次从数组中选择随机索引。

注意。这假定maximumAnswers 值将始终为&lt;=answerList.length + 1

var answerList = ["answer 1", "answer 2", "answer 3", "answer 4", "answer 5"];
var correctAnswer = "CORRECT!";
var selectedAnswers = [];
var maximumAnswers = 4;

function generateAnswers() {
    var tempAnswerList = shuffle(answerList); // lets create a clone of the answerList so we dont effect the original, and shuffle it
    tempAnswerList = tempAnswerList.slice(0, maximumAnswers - 1); // - 1 cos we will be adding the correct answer
    tempAnswerList.push(correctAnswer); // add correct answer to the 
    tempAnswerList = shuffle(tempAnswerList); // shuffle again so our correct answer isnt always last
    console.log(tempAnswerList);
}


// from http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript
function shuffle(o){ //v1.0
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

generateAnswers();

JSFIDDLE DEMO

【讨论】:

    【解决方案2】:

    我稍微更新了你的代码,因为我真的不明白你为什么要使用这么大的递归函数:

    var answerList = ["answer 1","answer 2", "answer 3", "answer 4", "answer 5"];
    var correctAnswer = "CORRECT!";
    var selectedAnswers = [correctAnswer];
    
    function wrong(answerList, number = 3) {
        //number means the number of answers you want as a return, I took the default as being 3
        var wrongAnswers = [];
        //While the wrongAnswer array is not filled as it should be:
        while (wrongAnswers.length < number && answerList.length > number) {
            //Take a new random value
            var random = Math.floor(Math.random() * answerList.length);
            //and add it to our array if it isn't already in there (indexOf)
            if (wrongAnswers.indexOf(answerList[random]) == -1) 
                 wrongAnswers.push(answerList[random]);
        }
        //If the list of possible answers is shorter than the number of answers you need as a return, just return all the possible answers, else return the generated list
        if (answerList.length <= number) 
            return answerList; 
        else 
            return wrongAnswers;
    }
    
    console.log(wrong(answerList));
    

    小提琴:http://jsfiddle.net/oybojgzm/2/

    【讨论】:

      【解决方案3】:
      /*
          Count: Number of answers to select
          answerPool: Array containing the possible answers
          selectedAnswers: Array that will be filled (possibly already containing elements)
      */
      function selectRandomFromAndPushInto(count, answerPool, selectedAnswers) {
          //Copy answerPool in case you want to reuse it for another call
          answerPool = answerPool.slice();
      
          //Iterate count times to select the random answers
          for(var iteration = 0; iteration < count; iteration ++) {
              //Find a random index in range 0 .. (answerPool.length - 1)
              var index = Math.round(Math.random() * (answerPool.length - 1));
              //Take the element at this index and push it into selectedAnswers
              selectedAnswers.push(answerPool[index]);
              //Remove the answer from answerPool, so that you won't select it again
              answerPool.splice(index, 1);
          }
      
          //Return the resulting array
          return selectedAnswers;
      }
      
      var answerPool = ["answer 1", "answer 2", "answer 3", "answer 4", "answer 5"];
      var selectedAnswers = ["CORRECT!"];
      console.log(selectRandomFromAndPushInto(3, answerPool, selectedAnswers));
      

      产生类似(使用 node.js 测试):

      [ 'CORRECT!', 'answer 3', 'answer 5', 'answer 4' ]
      

      【讨论】:

        【解决方案4】:

        简而言之:

        var answerList = ["answer 1", "answer 2", "answer 3", "answer 4", "answer 5"];
        var correctAnswer = "CORRECT!";
        var selectedAnswers = [correctAnswer];
        var randomNumber = 0;
        
        function randomAnswer() {
        while(selectedAnswers.length < 4){
            randomNumber = Math.floor(Math.random() * answerList.length);
            if(!(selectedAnswers.indexOf(answerList[randomNumber])>-1))
                selectedAnswers.push(answerList[randomNumber]);
            }
        }
        
        randomAnswer();
        

        http://jsfiddle.net/oybojgzm/5/

        【讨论】:

          【解决方案5】:

          考虑从一个可以在使用时测试的数组开始:

           var answerList = ["answer 1", "answer 2", "answer 3", "answer 4", "answer 5"];
           var correctAnswer = "CORRECT!";
           var selectedAnswers = [];
           var randomNumber, tmp, tm2, lng, i;
          
           function randomAnswer() {
             tmp=[];
             tm2=0; //number of elements currently in the tmp array
             lng=answerList.length; //save processing time by getting the length ONCE
             while(tm2<3) { //loop til we get 3 numbers in the tmp array
               randomNumber = Math.floor(Math.random() * lng); //array-index 0 thru (lng-1)
               for(i=0; i<tm2; i++) //first random number always is acceptable
                 if(tmp[i]==randomNumber) //if array-index is in the tmp array
                   break; //stop looping/looking; prevents i from equalling tm2
               if(i==tm2) //at end of UN-break'ed for loop, this would be true
                 tmp[tm2++]=randomNumber; //only different indices saved in tmp array
             }//end of while loop, which gets another random number until 3 different ones are selected
             //now put the correct answer somewhere, randomly, in the final array
             randomNumber = Math.floor(Math.random() * 3); //array-index 0 thru 2
             for(i=0; i<3; i++) {  //we know there are 3 indices in the tmp array
               if(i==randomNumber) //if our counter equals the random location for the answer
                 selectedAnswers.push(correctAnswer);  //put the real answer into the output
               selectedAnswers.push(answerList[tmp[i]]); //always put one of the other answers into the output
             }
             console.log(selectedAnswers);
           }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-10-25
            • 1970-01-01
            • 1970-01-01
            • 2021-04-05
            相关资源
            最近更新 更多