随机打乱数组

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

 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]

 

posted on 2018-10-19 09:27  大黑ylx  阅读(255)  评论(0编辑  收藏  举报