我有一个这样的数组:
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());
我希望这能帮助那些可能不太理解这一点的人。
其他回答
社区表示arr.sort((a,b)=>0.5-Math.random())不是100%随机的!对我测试并建议不要使用此方法!
let arr = [1, 2, 3, 4, 5, 6]
arr.sort((a, b) => 0.5 - Math.random());
但我不确定。所以我写了一些代码来测试!。。。你也可以试试!如果你足够感兴趣!
让data_base=[];对于(设i=1;i<=100;i++){//将100次新的rendom arr推送到data_base!数据基础推送([1,2,3,4,5,6]排序((a,b)=>{return Math.random()-0.5;//使用了社区禁止的方法!:-)}));}//console.log(data_base);//如果你想看数据!让分析={};for(设i=1;i<=6;i++){analysis[i]=阵列(6).填充(0);}for(假设num=0;num<6;num++){for(设i=1;i<=100;i++){let plus=数据基[i-1][num];分析[`${num+1}`][plus-1]++;}}console.log(分析);//分析结果
在100个不同的随机阵列中。(我的分析结果)
{ player> 1 2 3 4 5 6
'1': [ 36, 12, 17, 16, 9, 10 ],
'2': [ 15, 36, 12, 18, 7, 12 ],
'3': [ 11, 8, 22, 19, 17, 23 ],
'4': [ 9, 14, 19, 18, 22, 18 ],
'5': [ 12, 19, 15, 18, 23, 13 ],
'6': [ 17, 11, 15, 11, 22, 24 ]
}
// player 1 got > 1(36 times),2(15 times),...,6(17 times)
// ...
// ...
// player 6 got > 1(10 times),2(12 times),...,6(24 times)
正如你所看到的,这不是那么随机!苏。。。不要使用此方法!如果你测试多次,你会看到玩家1获得了很多次(1号)!而球员6在大多数时候都获得了(第6名)!
有趣的是,没有非变异递归答案:
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);
您可以通过以下方式轻松完成:
//阵列var fruits=[“香蕉”、“橙色”、“苹果”、“芒果”];//随机的,随机的fruits.sort(函数(a,b){return 0.5-Math.random()});//输出console.log(水果);
请参考JavaScript排序数组
你可以使用lodash洗牌。就像一个魅力
import _ from lodash;
let numeric_array = [2, 4, 6, 9, 10];
let string_array = ['Car', 'Bus', 'Truck', 'Motorcycle', 'Bicycle', 'Person']
let shuffled_num_array = _.shuffle(numeric_array);
let shuffled_string_array = _.shuffle(string_array);
console.log(shuffled_num_array, shuffled_string_array)
重建整个阵列,逐个将每个元素放在一个随机位置。
[1,2,3].reduce((a,x,i)=>{a.splice(Math.floor(Math.random()*(i+1)),0,x);return a},[])
变量ia=[1,2,3];var it=1000;var f=(a,x,i)=>{a.splice(Math.floor(Math.random()*(i+1)),0,x);返回a};var a=新数组(it).fill(ia).map(x=>x.reduce(f,[]));var r=新数组(ia.length).fill(0).map((x,i)=>a.reduce((i2,x2)=>x2[i]+i2,0)/it)console.log(“这些值应该相当相等:”,r);