Shuffle an Array 在 Javascript 中给出相同的值 [英] Shuffle an Array is giving the same value in Javascript
问题描述
我正在制作一个随机数组生成器,多次改组一个初始数组.
I'm making a generator of random arrays shuffling one initial array multiple times.
洗牌功能
const shuffle =(array) => {
let currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
GENERATE CHROMOSOMES(此函数生成一个数组数组,这些数组从初始数组随机化序列")
const generateChromosomes = (numberOfChromosomes) =>{
const result = [];
const sequence = ["2", "3", "4"];
for(let i = 1; i < numberOfChromosomes; i++){
result.push(shuffle(sequence))
}
return(result);
}
我不知道为什么,每次运行它时,我都没有得到不同的数组.我得到了 50 次相同的结果.当我重新运行代码时,它又给了我 50 倍.
I do not know why, each time when I run it, I don't get different arrays. I get 50 times the same one. When I re-run the code, it gives me 50 times another one.
推荐答案
很简单,我猜这个问题跟数组引用有关.将您的序列数组移动到循环中,以便您禁用引用器并通过变量的静态值设置随机播放.
Its simple, my guess is that this problem is related to the array reference. Move your sequence array into the loop so you disable the referer and set the shuffle by the static value of the variable.
const generateChromosomess = (numberOfChromosomes) => {
const result = [];
for(let i = 1; i < numberOfChromosomes; i++){
const sequence = ["2", "3", "4"]; // MOVE YOUR ARRAY HERE.
result.push(shuffle(sequence))
}
return(result);
}
有几种方法可以取消数组的引用 - via
There is few ways to cancel the reference of the array - via
JSON.parse(JSON.stringify(value))
或
[...value]
OR(通过 lodash
)
_.clone(array)
这篇关于Shuffle an Array 在 Javascript 中给出相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!