如果没有使用JavaScript跳到下一个,请检查数组元素是否存在

时间:2014-09-01 08:28:14

标签: javascript arrays

我正试图从一系列答案中抓取3个随机答案并将它们存储到一个新数组中。 因此,选择答案的新数组几乎会有来自答案池的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();

5 个答案:

答案 0 :(得分:1)

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

NB。这假定maximumAnswers值始终为<=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

答案 1 :(得分:0)

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

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/

答案 2 :(得分:0)

/*
    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' ]

答案 3 :(得分:0)

以非常短的方式:

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/

答案 4 :(得分:0)

考虑从您使用它时可以测试的数组开始:

 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);
 }