我有一个这样的数组:
var arr1 = ["a", "b", "c", "d"];
我如何随机化/打乱它?
我有一个这样的数组:
var arr1 = ["a", "b", "c", "d"];
我如何随机化/打乱它?
当前回答
罗纳德·费舍尔和弗兰克·耶茨洗牌
ES2015(ES6)版本
Array.prototype.shuffle2 = function () {
this.forEach(
function (v, i, a) {
let j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
);
return this;
}
Jet优化ES2015(ES6)版本
Array.prototype.shuffle3 = function () {
var m = this.length;
while (m) {
let i = Math.floor(Math.random() * m--);
[this[m], this[i]] = [this[i], this[m]];
}
return this;
}
其他回答
费希尔·耶茨在javascript中洗牌。我在这里发表这篇文章是因为与这里的其他答案相比,使用两个实用函数(swap和randInt)澄清了算法。
function swap(arr, i, j) {
// swaps two elements of an array in place
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
function randInt(max) {
// returns random integer between 0 and max-1 inclusive.
return Math.floor(Math.random()*max);
}
function shuffle(arr) {
// For each slot in the array (starting at the end),
// pick an element randomly from the unplaced elements and
// place it in the slot, exchanging places with the
// element in the slot.
for(var slot = arr.length - 1; slot > 0; slot--){
var element = randInt(slot+1);
swap(arr, element, slot);
}
}
可理解的洗牌数组元素的方法设arr1=[“a”,“b”,“c”,“d”];函数洗牌(数组){let currentIndex=array.length;while(currentIndex!=0){let randomIndex=Math.floor(Math.random()*array.length);当前索引-=1;let temp=数组[currentIndex];array[currentIndex]=array[randomIndex];array[randomIndex]=临时;}返回数组;}设arr2=洗牌(arr1);arr2.forEach(元素=>console.log(元素));
d3.js提供了Fisher–Yates shuffle的内置版本:
console.log(d3.shuffle([“a”,“b”,“c”,“d”]);<script src=“http://d3js.org/d3.v5.min.js“></script>
d3.洗牌(array[,lo[,hi]])<>使用Fisher–Yates混洗随机化指定阵列的顺序。
使用排序方法和数学方法:
var arr = ["HORSE", "TIGER", "DOG", "CAT"];
function shuffleArray(arr){
return arr.sort( () => Math.floor(Math.random() * Math.floor(3)) - 1)
}
// every time it gives random sequence
shuffleArr(arr);
// ["DOG", "CAT", "TIGER", "HORSE"]
// ["HORSE", "TIGER", "CAT", "DOG"]
// ["TIGER", "HORSE", "CAT", "DOG"]
使用underscore.js库。对于这种情况,方法_.shuffle()很好。以下是该方法的示例:
var _ = require("underscore");
var arr = [1,2,3,4,5,6];
// Testing _.shuffle
var testShuffle = function () {
var indexOne = 0;
var stObj = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5
};
for (var i = 0; i < 1000; i++) {
arr = _.shuffle(arr);
indexOne = _.indexOf(arr, 1);
stObj[indexOne] ++;
}
console.log(stObj);
};
testShuffle();