javascript如何在一个数组里随机选出不重复的10项?

[1,2,3,4,5,6,7,8,9,10,11,12,13,14]
在这个数组里选出10项不重复

眼眸繁星
浏览 747回答 1
1回答

慕容森

var&nbsp;result&nbsp;=&nbsp;[]; var&nbsp;arr&nbsp;=&nbsp;[1,2,3,4,5,6,7,8,9,10,11,12,13,14]; var&nbsp;len&nbsp;=&nbsp;arr.length; while(result.length&nbsp;<&nbsp;10){ &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;idx&nbsp;=&nbsp;parseInt(Math.random()*1000)%len&nbsp;; &nbsp;&nbsp;&nbsp;&nbsp;if(arr[idx]){ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.push(arr[idx]); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;arr[idx]&nbsp;=&nbsp;undefined; &nbsp;&nbsp;&nbsp;&nbsp;} }性能确实不如&nbsp;@边城&nbsp;的方法,我再添加一个性能更差但是简单的。arr&nbsp;=&nbsp;[1,2,3,4,5,6,7,8,9,10,11,12,13,14]; arr.sort(function(){return&nbsp;0.5-Math.random();}).slice(0,10);业余前端选手,从来不考虑性能。。。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript