循环以在每次迭代时修改变量,并附加每个新的"修改"到一个数组

时间:2015-08-04 03:14:14

标签: javascript arrays loops

我试图为游戏SET生成卡片组,或者,对于那些不知道那是什么的人,我试图用表单中的独特元素填充数组[a, b, c, d],其中0 <= a, b, c, d <= 2(81个元素)。所以,我想要[[0, 0, 0, 0,], [0, 0, 0, 1], ... , [2, 2, 2, 2]](顺序并不重要)。这是我到目前为止的代码:

var deck = [],
    count = [0, 0, 0, 0];
for (var i = 0; i < 81; i++) { // go through all combos
    deck.push(count); // append the current modification of count to deck
    // increment count by 1, carrying "tens" if necessary
    for (var j = 3; count[j] === 2; j--) {
        // if the "digit" is 2, make it 0 since it overflows
        count[j] = 0;
    }
    // j is the first "digit" of count that isn't already 2, so we add 1 to it
    count[j]++;
}

相反,这似乎做的是用最后修改deck填充count数组;如果i的上限是81,那么它是[0, 0, 0, 0],因为它一直翻转,如果你将边界更改为任何更低,它将相应地作出响应。为什么会这样?我犯了什么错误?

1 个答案:

答案 0 :(得分:1)

请记住,您每次迭代都会将同一count推送到deck,这意味着任何计数更改都会反映到count中的所有其他deck因为他们都引用了相同的array

您可以使用.slice克隆具有前一个count中相同值的新数组。

&#13;
&#13;
var deck = [],
    count = [0, 0, 0, 0];
for (var i = 0; i < 81; i++) { // go through all combos

    // Clone a new array from previous one.
    count = count.slice();


    deck.push(count); // append the current modification of count to deck
    // increment count by 1, carrying "tens" if necessary
    for (var j = 3; count[j] === 2; j--) {
        // if the "digit" is 2, make it 0 since it overflows
        count[j] = 0;
    }
    // j is the first "digit" of count that isn't already 2, so we add 1 to it
    count[j]++;
}
console.log(deck);
&#13;
&#13;
&#13;