JavaScript循环中如何每次迭代保存数组的当前修改值至moves数组?
数组引用导致moves存储值全部一致的问题解决
问题描述
遍历diceValues数组时,每次将当前项存入firstSplitDiceValues,同时把这个数组作为值存入moves数组,期望moves里每一项都记录firstSplitDiceValues的当前状态,但实际所有项都显示数组的最终值。
问题原因
JavaScript里数组是引用类型,你每次往moves里push的并不是当前数组的快照,而是指向firstSplitDiceValues的内存引用。循环结束后,所有引用都会指向同一个数组的最终状态,所以输出全是最后一次的结果。
解决方案
每次存入moves时,创建firstSplitDiceValues的副本,而不是直接存引用。常用的创建数组副本的方式有两种:
- 使用
slice()方法创建副本 - 使用扩展运算符
[...arr]创建副本
修改后的代码
方式一:用slice()创建副本
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]; moves.push([ { [tokens[diceValue]]: firstSplitDiceValues.slice() } ]); } console.log(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]; moves.push([ { [tokens[diceValue]]: [...firstSplitDiceValues] } ]); } console.log(moves);
验证结果
修改后运行代码,moves数组会符合预期输出:
[ [{"A": [1]}], [{"B": [1, 3]}], [{"C": [1, 3, 4]}], [{"D": [1, 3, 4, 6]}] ]
内容的提问来源于stack exchange,提问作者Olagoke Kay
相关产品推荐
相关产品推荐

