转载

随机打乱数组

  随机打乱数组元素,结果是无法预测的。

 1 function shuffle(arr) {  2     for (var i = 0; i < arr.length; i++) {  3         var index = parseInt(Math.random()*(arr.length-1));  4         var temp = arr[index];  5         arr[index] = arr[i];  6         arr[i] = temp;  7  }  8     return arr;  9 } 10 console.log(shuffle([1,2,3,4,5,6,7,8,9]));//[4, 3, 2, 7, 1, 8, 9, 5, 6]
11 console.log(shuffle([1,2,3,4,5,6,7,8,9]));//[9, 8, 6, 7, 1, 4, 5, 3, 2]
12 console.log(shuffle([1,2,3,4,5,6,7,8,9]));//[5, 8, 1, 4, 9, 3, 2, 6, 7]
13 console.log(shuffle([1,2,3,4,5,6,7,8,9]));//[8, 2, 5, 7, 9, 1, 6, 3, 4]
14 console.log(shuffle([1,2,3,4,5,6,7,8,9]));//[1, 5, 8, 9, 4, 2, 6, 7, 3]

 

转载于:https://www.cnblogs.com/daheiylx/p/9814592.html

正文到此结束
本文目录