Array.prototype.shuffle = function (n) { var len = this.length, num = n ? Math.min(n, len) : len, arr = this.slice(0); arr.sort(function (a, b) { returnMath.random() - 0.5; }); return arr.slice(0, num - 1); };
二、随机交换数组内的元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
lib = {}; lib.range = function (min, max) { return min + Math.floor(Math.random() * (max - min + 1)); };
Array.prototype.shuffle = function (n) { var len = this.length, num = n ? Math.min(n, len) : len, arr = this.slice(0), temp, index; for (var i = 0; i < len; i++) { index = lib.range(i, len - 1); temp = arr[i]; arr[i] = arr[index]; arr[index] = temp; } return arr.slice(0, num); };
三、随机从原数组抽取一个元素,加入到新数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
lib = {}; lib.range = function (min, max) { return min + Math.floor(Math.random() * (max - min + 1)); }; Array.prototype.shuffle = function (n) { var len = this.length, num = n ? Math.min(n, len) : len, arr = this.slice(0), result = [], index; for (var i = 0; i < num; i++) { index = lib.range(0, len - 1 - i); // 或者 result.concat(arr.splice(index,1)) result.push(arr.splice(index, 1)[0]); } return result; };