我想在同一个函数中随机混洗这两个数组
var array1 = [1,2,3,4,5];
var array2 = [6,7,8,9,10];以便它返回随机混洗的每个数组,例如
4,2,3,5,1
7,9,6,8,10另外,在返回时,我想在两者之间换行,请帮助?
发布于 2017-04-07 23:46:09
为方便访问,向Array.prototype添加了shuffle方法-返回一个修改后的数组,保持原始数组不变。
Array.prototype.shuffle = function() {
var rIndex, temp,
input = this.slice(0),
cnt = this.length;
while (cnt) {
rIndex = Math.floor(Math.random() * cnt);
temp = input[cnt - 1];
input[cnt - 1] = input[rIndex];
input[rIndex] = temp;
cnt--;
}
return input;
}
var array1 = [1, 2, 3, 4, 5];
var array2 = [6, 7, 8, 9, 10];
document.getElementById('shuffle-btn').onclick = function(){
document.getElementById('output').innerHTML = [array1.shuffle(), array2.shuffle()].join('\n');
}<button id="shuffle-btn">Shuffle</button>
<pre id="output"></pre>
https://stackoverflow.com/questions/43281492
复制相似问题