我有一个这样的数组:
var arr1 = ["a", "b", "c", "d"];
我如何随机化/打乱它?
我有一个这样的数组:
var arr1 = ["a", "b", "c", "d"];
我如何随机化/打乱它?
当前回答
我找不到我喜欢的。这是我想出的解决方案。我没有使用太多无意义的变量,因为这是我现在的编码方式。
Array.prototype.shuffle = function() {
for (let i in this) {
if (this.hasOwnProperty(i)) {
let index = Math.floor(Math.random() * i);
[
this[i],
this[index]
] = [
this[index],
this[i]
];
}
}
return this;
}
让arrayA=[“item1”、“item2”、“item3”、“Item 4”、“Items5”];Array.prototype.shuffle=函数(){为了(让我进来){如果(this.hasOwnProperty(i)){让index=Math.floor(Math.random()*i);[这个[i],此[索引]] = [该[索引],本[i]];}}返回此;}console.log(arrayA.shuffle());
我希望这能帮助那些可能不太理解这一点的人。
其他回答
// Create a places array which holds the index for each item in the
// passed in array.
//
// Then return a new array by randomly selecting items from the
// passed in array by referencing the places array item. Removing that
// places item each time though.
function shuffle(array) {
let places = array.map((item, index) => index);
return array.map((item, index, array) => {
const random_index = Math.floor(Math.random() * places.length);
const places_value = places[random_index];
places.splice(random_index, 1);
return array[places_value];
})
}
有趣的是,没有非变异递归答案:
var shuffle=arr=>{常量重复=(arr,currentIndex)=>{console.log(“什么?”,JSON.stringify(arr))如果(当前索引==0){返回arr;}const randomIndex=数学地板(Math.random()*当前索引);常量swap=arr[currentIndex];arr[currentIndex]=arr[randomIndex];arr[randomIndex]=掉期;返回重复(arr,当前索引-1);}返回递归(arr.map(x=>x),arr.length-1);};var arr=[1,2,3,4,5,[6];console.log(shuffle(arr));控制台日志(arr);
这里有简单的while循环
function ShuffleColor(originalArray) {
let shuffeledNumbers = [];
while (shuffeledNumbers.length <= originalArray.length) {
for (let _ of originalArray) {
const randomNumb = Math.floor(Math.random() * originalArray.length);
if (!shuffeledNumbers.includes(originalArray[randomNumb])) {
shuffeledNumbers.push(originalArray[randomNumb]);
}
}
if (shuffeledNumbers.length === originalArray.length)
break;
}
return shuffeledNumbers;
}
const colors = [
'#000000',
'#2B8EAD',
'#333333',
'#6F98A8',
'#BFBFBF',
'#2F454E'
]
ShuffleColor(colors)
为了更灵活,可以添加另一个参数。在这种情况下,可以从数组中获取一个随机数组,并指定新数组的长度:
function shuffle(array, len = array.length) {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array.slice(0, len);
}
var shuffle = function(array) {
temp = [];
originalLength = array.length;
for (var i = 0; i < originalLength; i++) {
temp.push(array.splice(Math.floor(Math.random()*array.length),1));
}
return temp;
};