Array.fill Shares One Reference Across Rows

new Array(n).fill(row) repeats one reference, so a write into any row mutates all of them; Array.from with a factory builds independent rows instead.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
// 反例:fill 填充数组时所有行共享同一个引用
const shared = new Array(3).fill(new Array(3).fill(0));
shared[0][0] = 9;
console.log('shared rows all mutate:', JSON.stringify(shared));

// 基础类型没有这个问题:每个槽位存的是值的拷贝
const zeros = new Array(3).fill(0);
zeros[1] = 5;
console.log('primitives stay independent:', JSON.stringify(zeros));

// 正确做法:工厂函数每行调用一次,各行彼此独立
const grid = Array.from({ length: 3 }, () => new Array(3).fill(0));
grid[2][2] = 7;
console.log('factory-built rows:      ', JSON.stringify(grid));

// new Array(3) 本身是稀疏数组:fill 之后才是稠密的
const holes = new Array(3);
console.log('sparse before fill: length', holes.length, 'first slot', holes[0], 'filled', holes.fill(1).length);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

shared rows all mutate: [[9,0,0],[9,0,0],[9,0,0]]
primitives stay independent: [0,5,0]
factory-built rows:       [[0,0,0],[0,0,0],[0,0,7]]
sparse before fill: length 3 first slot undefined filled 3

Inside the snippet

The file’s state is a handful of top-level bindings: shared, zeros, grid, holes.

Putting it to use

Running the file prints labeled results such as shared rows all mutate:, primitives stay independent:, factory-built rows: — each operation’s effect is visible in the output.

Core lines

const grid = Array.from({ length: 3 }, () => new Array(3).fill(0));

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `shared`, `zeros`, `grid`.