1. 程式人生 > >隨機抽取不重複的陣列元素

隨機抽取不重複的陣列元素

測試程式碼:

var arr0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; var ranNum0 = 5;
console.log(getDiffArr(arr0, ranNum0));   方法實現: 1.  不斷縮減原陣列,一次抽一個
        function getDiffArr(arr, num) {
            var arrOut = [];
            for (var i = 0; i < num; i++) {
                
var ran = Math.floor(Math.random() * arr.length); arrOut.push(arr[ran]); arr = (function (arr, ran) { var arrOut = []; for (var m = 0, n = arr.length; m < n; m++) { if (arr[m] != arr[ran]) { arrOut.push(arr[m]); } }
return arrOut; }(arr, ran)); } return arrOut; }

 

2.從抽第二個起,新陣列元素遍歷比較當前隨機元素,若抽到相同的則重抽

        function getDiffArr(arr, num) {
            var arrOut = [];
            var ran;
            for (var i = 0; i < num; i++) {
                ran 
= Math.floor(Math.random() * arr.length); // arrOut.push(arr[ran]); // error arrOut[i]=arr[ran]; if (i > 0) { for (var m = 0; m < i; m++) { if (arrOut[m] == arr[ran]) { i--; break; } } } } return arrOut; }