简体   繁体   中英

How can I add some randomness to populating this list?

I'm trying to populate a list of answers in a quiz. The correct answer is always the a0 in the data object. How can I make it so the first answer isn't always the correct one? A hint would be much appreciated!

data = [
        {"q":"How much?", "a0":"20%", "a1": "1%", "a2": "10%", "a3": "5%"},
        {"q":"What", "a0":"Ball", "a1": "Stone", "a2": "Bierd", "a3": "Carl"},
        {"q":"When?", "a0":"1999", "a1": "2000", "a2": "2001", "a3": "2002"}
        ];

function addData() {

var ids =['a','b','c','d'];
for (var j=0; j < ids.length; j++) {

    //Populate answers into list
    document.getElementById(ids[j]).innerHTML = data[q]['a'+j];

    //Add class 'correct' to the li with the right answer (always a0 in the data object)
    if (j==0) {
    document.getElementById(ids[j]).setAttribute('class', 'correct');
    }
};
}

<ul class="answers_quiz">
<li id="a"></li>
<li id="b"></li>
<li id="c"></li>
<li id="d"></li>
</ul>

Just sort the array using random numbers:

var ids =['a','b','c','d'];
ids.sort(function(x, y) {
    return parseInt(Math.random() * ids.length);
});
for (var j=0; j < ids.length; j++) {
    //.....
}

Live test case . (of the random sort)

You can generate a Random number and use it as a position of your array, always verifying the lenght of it and the number you got, of course.

You can generate a random number using something like that:

var randomnumber = Math.random();

you can sort array randomly as well as in sorting order.

Your array is String array and it doesnt matter that your answer comes in alphbetic order so you can try to sort it alphbetically.

following example is to sort string array.

//Sort alphabetically and ascending:
var myarray=["Bob", "Bully", "Amy"]
myarray.sort() //Array now becomes ["Amy", "Bob", "Bully"]

//Sort alphabetically and descending:
var myarray=["Bob", "Bully", "Amy"]
myarray.sort()
myarray.reverse() //Array now becomes ["Bully", "Bob", "Amy"]

refer http://www.javascriptkit.com/javatutors/arraysort.shtml

Now if you want to sort it by its index you can use following.

function randomSort(a,b) {
    return( parseInt( Math.random()*10 ) %2 );
}

var arlene = new Array( 1, 2, 3, 4, 5 );
alert( arlene.sort(randomSort).toString() );

refer http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/randomizeArrayElements.htm

This keeps the order of answers, changing just which is first.

Make random integer before the for loop: var offset=Math.floor(Math.random()*ids.length) , then first thing in loop do var idx='a'+((j+offset)%ids.length) . Instead of data[q]['a'+j] use data[q][idx] , and set class to correct when idx=="a0" instead of j==0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM