Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javascript数组随机排序 #8

Open
raclen opened this issue Sep 15, 2019 · 0 comments
Open

javascript数组随机排序 #8

raclen opened this issue Sep 15, 2019 · 0 comments
Labels
博客搬迁 以前博客的文章迁移过来

Comments

@raclen
Copy link
Owner

raclen commented Sep 15, 2019

数组随机排序又叫数组洗牌,我们在做一些抽奖的小游戏会用上
可能我从来用不上这个,但是,注意了,打起精神,面试可能会遇上哦

  var arr = [1,5,6,9];

    function shuffle(a){
    	var len = a.length,range;
    	var narr = [];
    	while(len){
    		range = Math.floor(Math.random()*len--);
    		narr.push(arr[range]);
    		arr.splice(range,1);
    	}
    	return narr;

    }
    console.log(shuffle(arr));
    //大神们说这里使用了splice复杂度比较高,那么效率就比较低
    //只有费雪耶茨洗牌才是标准,下面我们试着写写
    function shuffleplus(a){
    	//同样定义几个变量
    	var len = a.length,range;
    	//同样我们来遍历这个数组
    	while(len){
    		//同样我们来获得一个随机数
    		range  = Math.floor(Math.random()*len--);
    		//接下来怎么办呢,让我想想,我记得要换两次位置
    		//先把数组随机的数存下来
    		var temp = a[len];
    		a[len] = a[range];
    		//我不会写了/(ㄒoㄒ)/~~
    		a[range] = temp;

    	}
    	return a;

    }
    console.log(shuffleplus(arr))

延伸阅读
JavaScript 数组乱序
数组的完全随机排列
Fisher–Yates Shuffle
#2016-07-07

@raclen raclen added the 博客搬迁 以前博客的文章迁移过来 label Sep 15, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
博客搬迁 以前博客的文章迁移过来
Projects
None yet
Development

No branches or pull requests

1 participant