如何在 JavaScript 的单次迭代中修改数组并在循环外检索数组的相同修改值?

问题描述 投票:0回答:1

这个想法是循环遍历 diceValues 数组,并在每次迭代中,将循环中的当前项存储到名为“firstSplitDiceValues”的外部数组中。下面的代码块是一个非常简化的形式,用于概述挑战。

换句话说,每次迭代都应该继续构建firstSplitDiceValues的长度,同时这个firstSplitDiceValues应该作为值推送到另一个名为“moves”的数组中。

let firstSplitDiceValues = [];
const tokens = ['A', 'B', 'C', 'D'];
const diceValues = [1, 3, 4, 6];
const moves = [];

for (let diceValue=0; diceValue < diceValues.length; diceValue++) {
    firstSplitDiceValues[diceValue] = diceValues[diceValue];  // [1]
     
    moves.push([
       {
           [tokens[diceValue]]: firstSplitDiceValues
       }
    ]);
}
console.log(moves);

// What I expect:
// Moves array should contain:
[
    [{"A": [3, 4, 6]}],
    [{"B": [1, 4, 6]}],
    [{"C": [1, 3, 6]}],
    [{"D": [1, 3, 4]}]
]

// Actual results:
// Moves array only shows final expected value on all iterations
[
    [{"A": [1, 3, 4, 6]}],
    [{"B": [1, 3, 4, 6]}],
    [{"C": [1, 3, 4, 6]}],
    [{"D": [1, 3, 4, 6]}]
]

// What I expect:
// Moves array should contain:

[
    [{"A": [3, 4, 6]}],
    [{"B": [1, 4, 6]}],
    [{"C": [1, 3, 6]}],
    [{"D": [1, 3, 4]}]
]
javascript arrays loops for-loop
1个回答
0
投票

您将同一个数组firstSplitDiceValues 推送到内存中以在每次迭代中移动。相反,您希望为每次移动创建一个新数组并用适当的值填充它。您可以使用 slice() 来获得结果。这是更新后的代码。

const firstSplitDiceValues = [];
const tokens = ['A', 'B', 'C', 'D'];
const diceValues = [1, 3, 4, 6];
const moves = [];

for (let diceValue = 0; diceValue < diceValues.length; diceValue++) {
    const splitDiceValues = diceValues.slice(); // Create a shallow copy of diceValues
    const token = tokens[diceValue];
    splitDiceValues.splice(diceValue, 1); // Remove the current dice value from splitDiceValues
    moves.push([{ [token]: splitDiceValues }]);
}

console.log(moves);

我希望这能解决您的问题

© www.soinside.com 2019 - 2024. All rights reserved.