可以用sort排序方法
利用sort用法:arr.sort(compareFunction)
如果 compareFunction(a,b) 返回的值大于 0 ,则 b 在 a 的前边;
如果 compareFunction(a,b) 返回的值等于 0 ,则a 、b 位置保持不变;
如果 compareFunction(a,b) 返回的值小于 0 ,则 a 在 b 的前边。
let arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]; arr.sort(() => Math.random() - 0.5); //[2, 8, 3, 15, 6, 5, 14, 1, 9, 0, 11, 10, 16, 12, 13, 4, 7] //[13, 12, 8, 2, 4, 11, 5, 0, 6, 10, 1, 15, 9, 7, 14, 3, 16] //[8, 3, 13, 12, 4, 6, 7, 9, 11, 10, 16, 5, 2, 15, 1, 14, 0] //[12, 0, 2, 7, 11, 10, 1, 16, 5, 6, 9, 3, 14, 8, 13, 4, 15]
当然了 这个排序是有缺陷的 换了种 可以来看看
let arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]; function shuffle(arr) { let i = arr.length; while (i) { let j = Math.floor(Math.random() * i--); [arr[j], arr[i]] = [arr[i], arr[j]]; } return arr; } shuffle(arr); //[5, 14, 15, 8, 12, 13, 16, 2, 4, 7, 10, 6, 1, 11, 0, 9, 3] //[0, 13, 3, 15, 4, 9, 14, 1, 7, 10, 2, 5, 11, 8, 12, 16, 6] //[9, 13, 7, 11, 15, 5, 1, 6, 3, 16, 0, 10, 2, 12, 4, 8, 14] //[12, 11, 3, 16, 1, 2, 7, 10, 9, 14, 6, 5, 4, 8, 15, 0, 13]
循环随机 交换法
循环遍历该数组,在每次遍历中产生一个0 ~ length - 1的数,该数代表本次循环要随机交换的位置。
将本次循环当前位置的数和随机位置的数进行交换。
let arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]; for(let i = 0,len = arr.length; i < len; i++){ let currentRandom = parseInt(Math.random() * (len - 1)); let current = arr[i]; arr[i] = arr[currentRandom]; arr[currentRandom] = current; } //[15, 3, 1, 9, 13, 8, 10, 5, 7, 11, 12, 0, 16, 4, 6, 2, 14] //[15, 6, 3, 7, 8, 5, 9, 0, 13, 4, 12, 1, 11, 16, 14, 10, 2] //[1, 16, 10, 14, 13, 4, 6, 12, 5, 2, 9, 3, 8, 11, 15, 0, 7] //[2, 9, 10, 13, 12, 15, 16, 8, 1, 11, 14, 0, 3, 5, 4, 7, 6]