Trying to shuffle multiple arrays in javascript but in the same way? [duplicate]

◇◆丶佛笑我妖孽 提交于 2019-12-11 06:31:25

问题


I want to randomly shuffle these two arrays in the same function

var array1 = [1,2,3,4,5];
var array2 = [6,7,8,9,10];

So that it returns each array randomly shuffled such as

4,2,3,5,1
7,9,6,8,10

Also on return I want a line break between the two, please help?


回答1:


Added shuffle method to Array.prototype for easy access - returns a modified array keeping the original unchanged.

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/trying-to-shuffle-multiple-arrays-in-javascript-but-in-the-same-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!