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

Check if array element exist if not skip to next with JavaScript

本文关键字:检查 数组元素 是否 存在 下一个 JavaScript 如果不      更新时间:2023-09-26

我试图从一个答案数组中获取3个随机答案,并将它们存储到一个新数组中。因此,选择的新数组answers将从答案池中随机获得3个答案,再加上正确的Answer。我想我知道是什么得到了它,但唯一的问题是,如果已经使用了数组元素,我不知道如何让它跳过,而是添加一个不同的数组元素。所以我的新数组中出现了重复项。

请参阅此处的代码。

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

var answerList = ["answerswer 1", "answerswer 2", "answerswer 3", "answerswer 4", "answerswer 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();

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

注:。这假设maximumAnswers值将始终是<=answerList.length + 1

var answerList = ["answerswer 1", "answerswer 2", "answerswer 3", "answerswer 4", "answerswer 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演示

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

var answerList = ["answerswer 1","answerswer 2", "answerswer 3", "answerswer 4", "answerswer 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));

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

/*
    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 = ["answerswer 1", "answerswer 2", "answerswer 3", "answerswer 4", "answerswer 5"];
var selectedAnswers = ["CORRECT!"];
console.log(selectRandomFromAndPushInto(3, answerPool, selectedAnswers));

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

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

用很短的方式:

var answerList = ["answerswer 1", "answerswer 2", "answerswer 3", "answerswer 4", "answerswer 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/

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

 var answerList = ["answerswer 1", "answerswer 2", "answerswer 3", "answerswer 4", "answerswer 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);
 }