嵌套循环中的Javascript-Math.random每次都返回相同的序列



我试图在嵌套循环中随机化值:

let bools = {
first: true,
second: true,
third: true,
fourth: true,
fifth: true,
};
results = [];
for (let i = 0; i < 3; i++) {
for (let k in bools) {
bools[k] = Math.random() > 0.5;
console.log(bools[k]);
}
results.push({ i, bools });
}
console.log(results);

i的每次迭代的结果都是相同的序列。我对此感到困惑,并尝试了一个性能时间戳而不是随机数:

bools[k] = now() // from performance-now node package

并且它还为每次迭代返回相同精度的时间戳序列。这个告诉我的是内循环只运行一次。为什么不进行外for循环的每次迭代?我该怎么绕过这个?Thx:(

尝试替换:

results.push({ i, bools });

带有:

results.push({ i, bools: Object.assign({}, bools) });

您不断引用同一个对象"bools"并不断重写它,因此最终您将在"results"数组的每个元素中看到最后一次迭代的结果。另一方面,Object.assign({},bools(每次都从"bools"引用创建新对象。在这里阅读

最新更新