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

JavaScript使用Array.fill后push内部数组出现所有元素同步更新问题

问题原因

你的代码问题出在Array.fill()的特性上:当你向fill()方法传入非原始类型(对象、数组、函数等)时,数组的所有位置都会填充同一个引用地址的对象,并不是你预期的10个相互独立的对象。你在控制台看到的ref标识,就是控制台用来提示多个位置指向了同一个引用对象的标记。
所以你修改任意一个索引位置的stim数组,本质上都是修改同一个对象的属性,自然所有索引位置都会同步更新。

修复方案

你需要在创建数组时为每一个索引位单独生成新的对象,避免复用同一个引用,下面是两种可行的实现方式:

方案1:使用Array.from生成独立对象

Array.from的回调函数会在每个索引位执行一次,每次都会返回全新的对象:

const runs = {
  AC: {
    L: Array.from({length: 10}, () => ({
      stim: [],
      mask: [],
      resp: [],
      other: []
    })),
    R: Array.from({length: 10}, () => ({
      stim: [],
      mask: [],
      resp: [],
      other: []
    }))
  },
}

// 后续操作正常执行即可
let runData = runs["AC"]["R"][3]
runData.stim.push(40)
// 此时只有索引3的stim数组会被添加40,其他位置不受影响

方案2:使用for循环逐个创建对象

如果兼容性要求更高,可以用普通循环实现:

const runs = {
  AC: {
    L: [],
    R: []
  }
}
// 填充L数组
for(let i=0; i<10; i++){
  runs.AC.L.push({
    stim: [],
    mask: [],
    resp: [],
    other: []
  })
}
// 填充R数组
for(let i=0; i<10; i++){
  runs.AC.R.push({
    stim: [],
    mask: [],
    resp: [],
    other: []
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:36:03