这段代码到底哪里出错了??

function getRandRow(){
		var arr=[];
		for(var i=0;i<28;i++){
			arr[i]=i;
		}
		var len=28;
		var r=0;
		for(var i=0;i<20;i++){
			r=Math.floor(Math.random()*len);//随机索引
			arr[len-1]=arr[len-1]+arr[r]; //随机索引与最大索引交换
			arr[r]=arr[len-1]-arr[r]; 
			arr[len-1]=arr[len-1]-arr[r];
			len--; //最大索引自减
		}
		return arr;
	}
	console.log(getRandRow());

运行结果: 为什么会出现这么多的0 ????

http://img.mukewang.com/599c3db50001e55109350345.jpg

我的需求是 0-27 随机取出19个不重复的数 , 但是这段代码为什么会出现BUG??? 我快疯了

qq_0_39
浏览 1779回答 1
1回答

信者得救

错误的地方在于一种情况。就是len-1刚好等于r时。例如len-1=27,r刚好又是27时            arr[len-1]=arr[len-1]+arr[r]; //arr[27]=arr[27]+arr[27]            arr[r]=arr[len-1]-arr[r]; //arr[27]=arr[27]-arr[27],此时就会等于0了。            arr[len-1]=arr[len-1]-arr[r];//arr[27]=arr[27]-arr[27]解决办法:声明一个变量作为介质来传参。            var abc=arr[r];            arr[r]=arr[len-1];             arr[len-1]=abc;

慕瓜9220888

MMOAZZMZSIXFRNANIBWUJBUBYVIDSEMYLYXKHSXQFIVCMUWGMFTNUOYXZFPMAURPXTTZDAYLRCIFUFFTNLSIEDHLSJOOYUTDRFXAYCLBVVTIYXDCSIGUETBFEUIMJDHWZFLYJNAQZFUXBVCGAQDXDOICGFBQCEYVOBHSEQCFSVMIWVKJPZSPCASYKHAHSHBNGBOIYYECRDZCPMGNFHMYVIOYBZYKFPCCCWZBKXYVOBWEJJERLADQDYHTWJWPEFRNSPSCSOFRDHHNAKXXXGCGAEOKWCVLYSQKYTSFLYCGDKIYEKXRFJYZZOYOZAALKODTDXVURGUAGQAWGXWIYORVTTOMCCILWDRGMXNZJNLMHJHDCWKYBCBXDMAKRDIATOBPMTSEWMYYSZDAUPBYOBNKXIWIUGQMWPVAMGCZZFITVFQTPJPRBDSVREUHKWAJLYPJWPP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