如何添加一些随机性来填充此列表?

问题描述:

我试图在测验中填充答案列表。数据对象中的正确答案始终是a0。我怎样才能做到这一点,第一个答案并不总是正确的?一个提示将非常感谢!如何添加一些随机性来填充此列表?

JS:

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

HTML:

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

只需使用随机数数组排序:

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。 (随机排序的)

+0

完美的作品!谢谢 – jenswirf 2012-02-02 13:29:51

您可以生成一个随机数,并把它作为你的阵列的位置,始终验证它与该lenght当然,你有数。

您可以使用类似的东西产生一个随机数:

var randomnumber = Math.random(); 

您可以在排序顺序排序阵列随机以及。

你的数组是字符串数组,它并不重要,你的答案出现在alphbetic顺序,所以你可以尝试排序它alfolbetically。

下面的例子是对字符串数组进行排序。

//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"] 

参考http://www.javascriptkit.com/javatutors/arraysort.shtml

现在如果你想通过它的索引您可以使用下面对它进行排序。

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

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

参考http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/randomizeArrayElements.htm

这样可以保持答案的顺序,改变哪个是第一个。

让随机整数前的for循环:var offset=Math.floor(Math.random()*ids.length), 在环路,则第一件事情做var idx='a'+((j+offset)%ids.length)。而不是data[q]['a'+j]使用data[q][idx],并设置类更正idx=="a0"而不是j==0