可能重複:
How to randomize a javascript array?JavaScript中的一組數字的隨機排列
我寫的代碼在JavaScript中,我需要35個的輸入值,指定每個他們在一個數組中的地方,然後洗牌,這樣他們將以不同的順序重新排列。作爲這樣:
var sort = new Array(35);
sort[0] = document.getElementById("d1p1").value;
sort[1] = document.getElementById("d1p2").value;
// ...
// ... (till 35)
var rand1 = Math.floor(Math.random() * 35);
var rand2 = Math.floor(Math.random() * 35);
// ...
// ... (till 35)
var rsort = new Array(35);
rsort[rand1] = document.getElementById("d1p1").value;
rsort[rand2] = document.getElementById("d1p2").value;
唯一的問題是,由於Math.floor(的Math.random()* 35)生成一些相同的號碼從1-35不止一次(好,我想這是點的隨機性),那麼兩個值有時被分配相同的輸入框,並且它們返回 undefined。有任何想法嗎?
進行復印是VAR rsort = sort.slice容易()。 – Stefan
好點Stefan - 有不止一種方法去皮膚貓) –