You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript更新二维数组出现元素多次赋值问题的原因求解

问题根因

Array.prototype.fill()方法传入引用类型值(数组、对象等)时,填充的是同一个引用的浅拷贝,不会为每个位置生成独立的新实例。
你代码中m数组的所有行元素,实际指向同一个内存地址的子数组:修改m[0][0]等价于修改m[1][0],两次赋值操作作用在同一个数组元素上,最终就会出现值拼接、所有行内容完全一致的现象。

修复方案

不要直接用fill生成子数组,改用Array.from或者map方法,每次迭代生成独立的子数组实例即可:

const s = "ab";
// 写法1:使用Array.from生成每行独立数组
const m = Array.from({length: s.length}, () => Array(s.length).fill(""))

// 写法2:使用map生成每行独立数组
// const m = [...Array(s.length)].map(() => Array(s.length).fill(""))

for(let row = 0; row < s.length; row++) {
  for (let col = 0; col < s.length; col++) {
    m[row][col] += `<${row}${col}>`
  }
}

console.log(m) // 输出 [ [ '<00>', '<01>' ], [ '<10>', '<11>' ] ] 符合预期

内容的提问来源于stack exchange,提问作者Moni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 03:18:01