我必须得到一个没有1-20的数组,没有以随机顺序排列的重复。我可以使用的是一个函数Rand100(),它给出1-100之间的随机数?如果可能,请用javascript回答。
答案 0 :(得分:2)
这应该给你一个起点。我使用Math.random而不是Rand100 - 但它们应该产生类似的结果。 array_to_randomize是包含要随机化的元素的数组 random包含随机化的结果。
/* Array to Randomize */
var array_to_randomize = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t"]
/* Results */
var random = [];
var j = 0,
i = array_to_randomize.length;
while (i > 0){
j = Math.random() * array_to_randomize.length;
random.push(array_to_randomize.splice(j,1))
i = array_to_randomize.length;
}
random.forEach(function(value,index){console.log("index: " + index + " value: " + value)})
答案 1 :(得分:2)
var sampleArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var arrayTemp = [];
for (var i = 20;i>=0;i--){
var temp = Rand100()%i;
arrayTemp.push(sampleArray[temp]);
sampleArray.splice(temp,1);
};
console.log(arrayTemp);