我有一个这样的数组:
var arr1 = ["a", "b", "c", "d"];
我如何随机化/打乱它?
我有一个这样的数组:
var arr1 = ["a", "b", "c", "d"];
我如何随机化/打乱它?
当前回答
警告不建议将此答案用于随机化大型阵列、密码学或任何其他需要真正随机性的应用程序,因为其存在偏差且效率低下。元素的位置只是半随机的,它们将倾向于保持更接近其原始位置。看见https://stackoverflow.com/a/18650169/28234.
可以使用Math.random任意决定是否返回1:-1:
[1, 2, 3, 4].sort(() => (Math.random() > 0.5) ? 1 : -1)
尝试运行以下示例:
常量数组=[1,2,3,4];//基于Math.Random返回的值,//任意决定是否返回1:-1const shuffeled=array.sort(()=>{const randomTrueOrFalse=数学random()>0.5;return randomTrueOrFalse?1 : -1});console.log(shuffeled);
其他回答
警告不建议将此答案用于随机化大型阵列、密码学或任何其他需要真正随机性的应用程序,因为其存在偏差且效率低下。元素的位置只是半随机的,它们将倾向于保持更接近其原始位置。看见https://stackoverflow.com/a/18650169/28234.
可以使用Math.random任意决定是否返回1:-1:
[1, 2, 3, 4].sort(() => (Math.random() > 0.5) ? 1 : -1)
尝试运行以下示例:
常量数组=[1,2,3,4];//基于Math.Random返回的值,//任意决定是否返回1:-1const shuffeled=array.sort(()=>{const randomTrueOrFalse=数学random()>0.5;return randomTrueOrFalse?1 : -1});console.log(shuffeled);
可以(但不应该)将其用作Array中的原型:
来自ChristopheD:
Array.prototype.shuffle = function() {
var i = this.length, j, temp;
if ( i == 0 ) return this;
while ( --i ) {
j = Math.floor( Math.random() * ( i + 1 ) );
temp = this[i];
this[i] = this[j];
this[j] = temp;
}
return this;
}
Fisher Yates的另一个实现,使用严格模式:
function shuffleArray(a) {
"use strict";
var i, t, j;
for (i = a.length - 1; i > 0; i -= 1) {
t = a[i];
j = Math.floor(Math.random() * (i + 1));
a[i] = a[j];
a[j] = t;
}
return a;
}
罗纳德·费舍尔和弗兰克·耶茨洗牌
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;
}
对CoolAJ86答案的简单修改,不修改原始数组:
/**
* Returns a new array whose contents are a shuffled copy of the original array.
* @param {Array} The items to shuffle.
* https://stackoverflow.com/a/2450976/1673761
* https://stackoverflow.com/a/44071316/1673761
*/
const shuffle = (array) => {
let currentIndex = array.length;
let temporaryValue;
let randomIndex;
const newArray = array.slice();
// While there remains elements to shuffle...
while (currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// Swap it with the current element.
temporaryValue = newArray[currentIndex];
newArray[currentIndex] = newArray[randomIndex];
newArray[randomIndex] = temporaryValue;
}
return newArray;
};