【JS】随机打乱数组的方法

一 数组对象

使用

this.list=[
	{
    
    src:'https://bjetxgzv.cdn.bspapp.com/VKCEYUGU-hello-uniapp/2cc220e0-c27a-11ea-9dfb-6da8e309e0d8.mp3',num:0},
	{
    
    src:'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/2minute-demo.mp4',num:1},
	{
    
    src:'22',num:2},
	{
    
    src:'33',num:3},
	{
    
    src:'44',num:4}]
this.list = this.shuffle(this.list);
console.log(this.list)

随机播放列表案例
首先要明确,我们对播放列表打乱的前提是不能对原数组进行更改的

//获取min和max之间的一个随机整数[5,100];
function getRandomInt(min,max){
    
    
	return Math.floor(Math.random()*(max-min+1))+min;
}

//打乱数组
function shuffle(arr){
    
    
	let _arr = arr.slice(); //slice不会影响原来的数组,但是splice就会影响原来的arr数组
	for (let i = 0; i<_arr.length; i++;){
    
    
		let j = getRandomInt(0,i);
		let t = _arr[i];
		_arr[i] = _arr[j];
		_arr[j] = t;
	}
	return _arr;
}

二 纯数字数组

var a = [1, 2, 3, 4, 5];
a.sort(randomSort);
console.log(a);
function randomSort(a, b) {
    
     return Math.random() > 0.5 ? -1 : 1; }

结果:[5, 3, 2, 1, 4]

猜你喜欢

转载自blog.csdn.net/AAAXiaoApple/article/details/132491585