方法1:
给数组原生的sort方法传入一个函数,此函数随机返回1或-1,达到随机排列数组元素的目的。
const arr1 = [1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9]
const shuffleArray = (arr) => arr.sort(() =>{return Math.random()>0.5?-1:1})
console.log(shuffleArray(arr1))
运行结果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/39bb22e5622e48a0a12b27556e38d638.png)
方法2:
为Array.prototype添加一个函数。
if (!Array.prototype.shuffle) {
Array.prototype.shuffle = function() {
for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
return this;
};
}
const arr = [1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9]
const shuffleArray = arr.shuffle()
console.log(shuffleArray)
运行结果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/3443dcdde4e94814bca31ce8a7526896.png)
方法一:直观,但是效率低;
方法二:更加高效。