[英]Loop to modify a variable each iteration, and append each new “modification” to an array
我正在尝试为游戏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]++;
}
相反,这似乎是用count
的最后一个修改填充deck
数组; 如果i
的上限为81,则此值为[0, 0, 0, 0]
因为它会一直滚动,如果将界限更改为下限,它将相应地响应。 为什么会这样? 我犯了什么错误?
只需记住,您每次迭代都将相同的count
推入deck
,这意味着要计数的任何更改都将反映给deck
所有其他count
,因为它们都引用同一array
您可以使用.slice
克隆一个具有与先前count
相同值的新数组。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.