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

JavaScript中Array.fill([])引发单元素修改致全数组变更问题

问题原因与解决方案

这是个非常典型的JavaScript引用类型陷阱!我刚学JS的时候也踩过一模一样的坑 😅

为什么会出现这个问题?

当你执行Array(7).fill([])时,你并不是创建了7个独立的空数组——而是把同一个空数组的内存引用复制到了新数组的7个位置上。也就是说,openingSegments[0]、openingSegments[1]……直到openingSegments[6],它们指向的都是同一个数组对象。所以当你给openingSegments[0]push元素时,所有位置的“数组”其实都是同一个东西,自然都会显示新增的元素。

正确的写法

下面几种方式都能创建包含7个独立空数组的新数组,随便选一种你喜欢的就行:

方法1:用Array.from(最简洁推荐)

Array.from可以在创建数组的同时,为每个位置生成独立的数组实例:

let openingSegments = Array.from({ length: 7 }, () => []);
openingSegments[0].push({'start': '1100', 'end': '1900'});
console.log(openingSegments);

方法2:结合fill和map

先填充占位值(比如undefined),再用map为每个位置生成新数组:

let openingSegments = Array(7).fill().map(() => []);
openingSegments[0].push({'start': '1100', 'end': '1900'});
console.log(openingSegments);

方法3:传统循环(适合新手理解原理)

手动循环创建每个独立数组,最直观:

let openingSegments = [];
for (let i = 0; i < 7; i++) {
  openingSegments.push([]);
}
openingSegments[0].push({'start': '1100', 'end': '1900'});
console.log(openingSegments);

核心要点就是:引用类型(数组、对象)不能直接用fill批量创建,否则会导致所有元素共享同一个引用,必须确保每个元素都是新创建的独立实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:00:21