在另一个二维数组中复制随机数组
Issue copying shuffled arrays in another 2 dimensions array
编辑(已解决): 这只是我对数组在 JS 中的工作方式的误解。 感谢 Nicholas Tower 的回答。
原文post:
标题:使用 for-loop 中的函数修改二维数组的闭包问题。
我有一个包含一组字符串 (rotationsSet) 的数组,我想用 8 个随机版本的 rotationsSet 填充另一个数组。 我的二维数组最终用最后一组随机字符串填充了 8 次。
我是 Web 开发人员和 JS 的新手,但从我读到的内容来看,这似乎是一个关闭问题。 我尝试在 initShuffledSets 函数中使用 forEach 循环而不是 for 循环,但结果相同。
var numberOfCubes = 8;
var rotationsSet = [
'rotateX(90deg)',
'rotateX(-90deg)',
'rotateY(90deg)',
'rotateY(-90deg)',
'rotateX(180deg)'
];
var shuffledRotationsSets = Array(numberOfCubes).fill(['']);
// Fisher-Yates array shuffle
function shuffle(array) {
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]];
}
}
function initShuffledSets() {
for (let z = 0; z < shuffledRotationsSets.length; z++) {
shuffledRotationsSets[z] = rotationsSet;
shuffle(shuffledRotationsSets[z]);
}
}
initShuffledSets();
A for-loop 中的 console.log 显示 8 个不同的数组(这就是我想要的),而 for-loop 之外的控制台日志显示 8 个相同的数组对应于最后一次洗牌数组。
创建数组只有一行代码:
var rotationsSet = [
'rotateX(90deg)',
'rotateX(-90deg)',
'rotateY(90deg)',
'rotateY(-90deg)',
'rotateX(180deg)'
];
其他一切都只是引用完全相同的数组。这行代码不创建副本:
shuffledRotationsSets[z] = rotationsSet;
shuffledRotationsSets[0]、shuffledRotationsSets[1]、shuffledRotationSets[2]等都是同一个数组,只是引用方式不同而已。因此,稍后当您开始通过交换其元素来改变数组时,任何引用该数组的内容都会 "see" 发生变化。
如果你想要可以单独变异的独立数组,你需要复制它。要创建副本,有几个选项。您可以使用 array.slice():
shuffledRotationsSets[z] = rotationsSet.slice();
或者您可以创建一个数组文字并将旧数组散布到其中:
shuffledRotationsSets[z] = [...rotationsSet];