JavaScript fill() 填充陷阱:共享引用、区间边界与失败后的部分修改
初始化三个待办项,只勾选第一项,另外两项却一起变成完成状态。遇到这种现象,先检查是否写了 new Array(3).fill({ done: false }):三个位置保存的是同一个对象,不是三个对象副本。
本文只拆解 Array.prototype.fill 的填充契约:值的身份、半开区间、稀疏位置、类数组与写入失败。配套实验在 Node.js v24.19.0 上运行,包含 40 个独立案例与 10 个故意写错的语义变体,不涉及性能排名或完整 polyfill 实现。
概念示意图:左侧三个槽位指向同一对象,右侧每个槽位指向单独创建的对象。配图为本篇独立模型生成的教学插图,不是真实运行截图。
一、先解决共享引用,再看填充区间
fill(value, start, end) 会把同一个 value 写入选定位置。value 是对象时,复制的是引用;value 是函数时,函数本身也是填充值,不会被当作工厂逐次调用。需要独立对象,就把创建动作放进循环,每轮创建一次。替换某一个数组槽位,和修改共享对象的属性,是两种不同操作。参见 MDN:Array.prototype.fill。
把下面完整内容保存为 example.cjs,运行 node example.cjs。这里使用普通循环展示独立创建,不把问题扩展成其他数组方法的比较。
const shared = new Array(3).fill({ done: false });
shared[0].done = true;
const independent = [];
for (let i = 0; i < 3; i += 1) independent.push({ done: false });
independent[0].done = true;
const values = [0, 1, 2, 3, 4];
const returned = values.fill(9, -4, -1);
const sparse = new Array(3);
sparse.fill(undefined, 1, 2);
const partial = [0, 1, 2];
Object.defineProperty(partial, '1', {
value: 1, writable: false, enumerable: true, configurable: true
});
let error = null;
try { partial.fill(9); }
catch (caught) { error = caught.name; }
console.log(JSON.stringify({
shared: [shared[0].done, shared[1].done, shared[2].done],
independent: [independent[0].done, independent[1].done, independent[2].done],
sameObject: shared[0] === shared[1],
values,
returnedSame: returned === values,
sparseOwnKeys: Object.keys(sparse),
partial: { error, values: partial }
}, null, 2));下面是固定预期输出,同时保存为 example.expected.json,稍后的校验程序会直接读取它。shared 的三个 true 来自同一对象被修改;independent 只有第一个位置改变。
{
"shared": [
true,
true,
true
],
"independent": [
true,
false,
false
],
"sameObject": true,
"values": [
0,
9,
9,
9,
4
],
"returnedSame": true,
"sparseOwnKeys": [
"1"
],
"partial": {
"error": "TypeError",
"values": [
9,
1,
2
]
}
}returnedSame 为 true 表示返回的就是接收者数组,不能靠接住返回值获得副本。sparseOwnKeys 只有 "1",说明选定的空槽被写成了“存在且值为 undefined”的属性;其他空槽没有被顺便填满。用 JSON.stringify 单独观察稀疏数组容易混淆空槽与 undefined,因此实验额外检查自有属性。
二、start 与 end 要先转换,再形成半开区间
最终写入范围包含起点、不包含终点,记作 [start, end)。可以按以下顺序手算:先将边界转为数值并向零截断小数,再把负数解释为相对初始长度的位置,最后夹到 0 至长度之间。当前 ECMAScript 工作草案的 fill 算法使用 ToClampedIndex 表达这套边界规则;它不是新增的填充功能。
长度为 5 时,fill(9, 1, 3) 只写索引 1、2;fill(9, -4, -1) 写索引 1、2、3。
省略 start 相当于从 0 开始。省略 end 或显式传 undefined,终点取读取到的长度;null 转为 0,不能当作“省略终点”。
NaN 转为 0。因此 NaN 用作起点可能仍然填充,用作终点则可能得到空区间。无效数字字符串也会走到 NaN 的转换结果。
1.9 截为 1,-2.9 截为 -2,-0.9 截为 0。后者不是从末尾退一位,不能用 Math.floor 替代向零截断。
-Infinity 夹到 0,Infinity 夹到长度。起点过大、终点过小,或者转换后的起点不小于终点,都不会进入写入循环。
BigInt 与 Symbol 不能用于这里的隐式 Number 转换,会抛出 TypeError;错误信息的文字不属于本文的断言内容。
转换细节依据 ToIntegerOrInfinity 与 ToClampedIndex。空区间只保证不执行逐项写入,不保证没有副作用:length 读取、start 转换和 end 转换仍可能触发用户代码或抛错。第 37 个案例专门记录空区间中的转换顺序。
三、借给类数组使用时,长度和值是两回事
fill 可以通过 Reflect.apply 或 call 借给普通对象。实验中的 { length: '3' } 会按长度 3 选择索引,但原来的 length 属性仍保留字符串 '3';长度 2.8 按 2 使用,负长度或缺失长度按 0 使用。这不要求对象实现迭代器。长度转换的上限是 2 的 53 次方减 1,本文不构造超大循环来测试上限。
算法先读取 length 一次,再转换 start、end,随后逐项写入。案例 32 把三个动作记入日志,并在 start 转换时改变 getter 之后会返回的长度,验证本次边界仍使用先前读取的长度。依据 LengthOfArrayLike 与 ToLength。
对于没有副作用的边界参数、没有特殊索引访问器的普通数组,fill 不会延长数组。不要把这句话扩展成“任意接收者的 length 永远不变”:参数转换、getter、setter 或 Proxy 可以自行改变对象;那是用户代码的副作用,不能被这条简写掩盖。
四、写到一半失败,之前的修改不会自动撤销
example.cjs 把索引 1 定义为不可写,其他索引保留正常可写状态。fill 先把索引 0 改成 9,随后在索引 1 失败,索引 2 还没有轮到,因此留下 [9, 1, 2]。这不是全有或全无的事务。
索引写入按升序进行。规范在每次写入时使用 Set 的抛错标志 true,因此不能指望“调用文件没有 use strict 就静默跳过”。本文同时运行普通 Node 与 --use-strict,验证该例在两种启动方式下都抛 TypeError。依据 ECMAScript:Set。
测试只在新建的局部对象上配置描述符,并明确写出可写、可枚举、可配置选项,不改 Array.prototype,也不修改全局原型。getter-only 属性没有 setter 会导致写入失败;有 setter 则调用 setter,而不是直接把访问器替换成数据属性。不可扩展数组中已有的可写元素仍能改,缺失位置的新增可能失败。描述符含义可核对 MDN:Object.defineProperty。
实务上,如果后续逻辑要求整批成功,先确认数据结构确实是你控制的普通可写数组。不要仅仅 catch 后继续处理,就假定数据仍是原来的样子;也不要把这里有限的检查包装成安全加固方案。
五、40 个独立案例与 10 个错误变体
保存下面完整文件为 fill-lab.cjs。每个案例重新创建接收者,固定预期值在运行前手工写好;案例列表、案例记录和预期数据均被冻结,待填充的输入不会被冻结。冻结是防止实验误改预期,不代表对任意代码的安全隔离。
01 至 08:默认填充、返回身份、对象别名、单槽替换、函数值、空槽与 undefined。
09 至 27:半开边界、负索引、裁剪、空区间、undefined/null/NaN、小数、无穷与数字字符串。
28 至 32:类数组长度及读取、转换顺序。
33 至 40:部分修改、描述符、setter、不可扩展对象、空区间转换及非法输入。
10 个变体故意引入对象克隆、包含终点、负数归零、向下取整、NaN 终点默认化、保留空槽、返回副本、只接收数组、吞掉异常和倒序写入这十类错误。每个变体有一个指定的语义反例,也会运行全部 40 个案例。KILL 表示观察结果与固定预期不同,不是程序崩溃次数或安全漏洞数量。
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const nativeFill = (target, ...args) =>
Reflect.apply(Array.prototype.fill, target, args);
// Freeze the oracle, not the fresh receiver that fill must mutate.
function freezeData(value) {
if (value && typeof value === 'object') {
for (const child of Object.values(value)) freezeData(child);
Object.freeze(value);
}
return value;
}
function test(id, run, expected) {
return Object.freeze({ id, run, expected: freezeData(expected) });
}
function errorName(action) {
try { action(); return null; }
catch (error) { return error.name; }
}
function range(fill, ...bounds) {
const a = [0, 1, 2, 3, 4];
fill(a, 9, ...bounds);
return a;
}
function ownSlots(a, count) {
const result = [];
for (let i = 0; i < count; i += 1) {
result.push(Object.hasOwn(a, i) ? a[i] : '<hole>');
}
return result;
}
const cases = Object.freeze([
test('01-default', f => range(f), [9, 9, 9, 9, 9]),
test('02-return-identity', f => {
const a = [1, 2];
return [f(a, 7) === a, a.length, a[0], a[1]];
}, [true, 2, 7, 7]),
test('03-object-alias', f => {
const value = { count: 0 };
const a = new Array(3);
f(a, value);
a[0].count += 1;
return [a[0] === a[1], a[1] === value, a[2].count, value.count];
}, [true, true, 1, 1]),
test('04-replace-one-slot', f => {
const value = { count: 0 };
const a = new Array(3);
f(a, value);
a[0] = { count: 8 };
return [a[0] === a[1], a[1] === a[2], value.count, a[0].count];
}, [false, true, 0, 8]),
test('05-function-is-value', f => {
let calls = 0;
const factory = () => { calls += 1; return {}; };
const a = new Array(2);
f(a, factory);
return [calls, a[0] === factory, a[1] === factory];
}, [0, true, true]),
test('06-fill-all-holes', f => {
const a = new Array(3);
f(a, 6);
return [ownSlots(a, 3), Object.keys(a)];
}, [[6, 6, 6], ['0', '1', '2']]),
test('07-fill-selected-holes', f => {
const a = new Array(4);
f(a, 6, 1, 3);
return ownSlots(a, 4);
}, ['<hole>', 6, 6, '<hole>']),
test('08-undefined-is-present', f => {
const a = new Array(2);
f(a, undefined);
return [Object.hasOwn(a, 0), Object.hasOwn(a, 1), a[0] === undefined];
}, [true, true, true]),
test('09-half-open', f => range(f, 1, 3), [0, 9, 9, 3, 4]),
test('10-start-only', f => range(f, 3), [0, 1, 2, 9, 9]),
test('11-negative-start', f => range(f, -2), [0, 1, 2, 9, 9]),
test('12-negative-end', f => range(f, 1, -1), [0, 9, 9, 9, 4]),
test('13-both-negative', f => range(f, -4, -2), [0, 9, 9, 3, 4]),
test('14-clamp-bounds', f => range(f, -99, 99), [9, 9, 9, 9, 9]),
test('15-start-past-length', f => range(f, 99), [0, 1, 2, 3, 4]),
test('16-reversed-range', f => range(f, 4, 2), [0, 1, 2, 3, 4]),
test('17-zero-end', f => range(f, 0, 0), [0, 1, 2, 3, 4]),
test('18-undefined-end', f => range(f, 2, undefined), [0, 1, 9, 9, 9]),
test('19-null-end', f => range(f, 0, null), [0, 1, 2, 3, 4]),
test('20-nan-start', f => range(f, NaN, 2), [9, 9, 2, 3, 4]),
test('21-nan-end', f => range(f, 0, NaN), [0, 1, 2, 3, 4]),
test('22-positive-fractions', f => range(f, 1.9, 3.9), [0, 9, 9, 3, 4]),
test('23-negative-fractions', f => range(f, -2.9, -0.9), [0, 1, 2, 3, 4]),
test('24-infinite-bounds', f => range(f, -Infinity, Infinity), [9, 9, 9, 9, 9]),
test('25-positive-infinite-start', f => range(f, Infinity), [0, 1, 2, 3, 4]),
test('26-negative-infinite-end', f => range(f, 0, -Infinity), [0, 1, 2, 3, 4]),
test('27-string-bounds', f => range(f, '1', '3'), [0, 9, 9, 3, 4]),
test('28-generic-string-length', f => {
const o = { 0: 'a', 3: 'keep', length: '3' };
const same = f(o, 'x', 1) === o;
return [same, o[0], o[1], o[2], o[3], o.length];
}, [true, 'a', 'x', 'x', 'keep', '3']),
test('29-generic-fractional-length', f => {
const o = { length: 2.8 };
f(o, 'x');
return [ownSlots(o, 3), o.length];
}, [['x', 'x', '<hole>'], 2.8]),
test('30-generic-negative-length', f => {
const o = { 0: 'keep', length: -2 };
f(o, 'x');
return [o[0], o.length, Object.hasOwn(o, 1)];
}, ['keep', -2, false]),
test('31-generic-missing-length', f => {
const o = { 0: 'keep' };
return [f(o, 'x') === o, Object.keys(o)];
}, [true, ['0']]),
test('32-length-and-conversion-order', f => {
const log = [];
const o = {};
let lengthNow = 3;
Object.defineProperty(o, 'length', {
get() { log.push('length'); return lengthNow; },
enumerable: true, configurable: true
});
const start = { valueOf() { log.push('start'); lengthNow = 1; return 0; } };
const end = { valueOf() { log.push('end'); return 3; } };
f(o, 'x', start, end);
return [log, ownSlots(o, 3), lengthNow];
}, [['length', 'start', 'end'], ['x', 'x', 'x'], 1]),
test('33-partial-write', f => {
const a = [0, 1, 2];
Object.defineProperty(a, '1', {
value: 1, writable: false, enumerable: true, configurable: true
});
const error = errorName(() => f(a, 9));
return [error, a[0], a[1], a[2]];
}, ['TypeError', 9, 1, 2]),
test('34-getter-only-failure', f => {
const o = { 1: 'keep', length: 2 };
let reads = 0;
Object.defineProperty(o, '0', {
get() { reads += 1; return 'old'; },
enumerable: true, configurable: true
});
const error = errorName(() => f(o, 'x'));
return [error, reads, o[1]];
}, ['TypeError', 0, 'keep']),
test('35-setter-receives-value', f => {
const o = { length: 2 };
const log = [];
Object.defineProperty(o, '0', {
set(value) { log.push(value); },
enumerable: true, configurable: true
});
const same = f(o, 'x') === o;
const d = Object.getOwnPropertyDescriptor(o, '0');
return [same, log, o[1], Object.hasOwn(d, 'value')];
}, [true, ['x'], 'x', false]),
test('36-nonextensible-hole', f => {
const a = [0, , 2];
Object.preventExtensions(a);
const error = errorName(() => f(a, 9));
return [error, ownSlots(a, 3)];
}, ['TypeError', [9, '<hole>', 2]]),
test('37-empty-still-converts', f => {
const a = [0, 1];
Object.defineProperty(a, '0', {
value: 0, writable: false, enumerable: true, configurable: true
});
const log = [];
const start = { valueOf() { log.push('start'); return 1; } };
const end = { valueOf() { log.push('end'); return 1; } };
return [f(a, 9, start, end) === a, log, a[0], a[1]];
}, [true, ['start', 'end'], 0, 1]),
test('38-bigint-start', f => {
const a = [0, 1];
return [errorName(() => f(a, 9, 1n)), a];
}, ['TypeError', [0, 1]]),
test('39-symbol-end', f => {
const a = [0, 1];
return [errorName(() => f(a, 9, 0, Symbol('end'))), a];
}, ['TypeError', [0, 1]]),
test('40-null-receiver', f => errorName(() => f(null, 9)), 'TypeError')
]);
// These are deliberately WRONG teaching variants, not fill polyfills.
const mutants = Object.freeze([
Object.freeze({ id: 'M01-clone-each', witness: '03-object-alias', fill(o, v, ...b) {
const result = nativeFill(o, v, ...b);
if (v && typeof v === 'object') {
for (let i = 0; i < o.length; i += 1) {
if (o[i] === v) o[i] = { ...v };
}
}
return result;
} }),
Object.freeze({ id: 'M02-inclusive-end', witness: '09-half-open', fill(o, v, s, e) {
return nativeFill(o, v, s, typeof e === 'number' ? e + 1 : e);
} }),
Object.freeze({ id: 'M03-negative-as-zero', witness: '11-negative-start', fill(o, v, s, e) {
return nativeFill(o, v, s < 0 ? 0 : s, e < 0 ? 0 : e);
} }),
Object.freeze({ id: 'M04-floor-fractions', witness: '23-negative-fractions', fill(o, v, s, e) {
const floor = x => typeof x === 'number' ? Math.floor(x) : x;
return nativeFill(o, v, floor(s), floor(e));
} }),
Object.freeze({ id: 'M05-nan-end-default', witness: '21-nan-end', fill(o, v, s, e) {
return nativeFill(o, v, s, Number.isNaN(e) ? undefined : e);
} }),
Object.freeze({ id: 'M06-preserve-holes', witness: '06-fill-all-holes', fill(o, v, ...b) {
const missing = [];
for (let i = 0; i < o.length; i += 1) {
if (!Object.hasOwn(o, i)) missing.push(i);
}
const result = nativeFill(o, v, ...b);
for (const i of missing) delete o[i];
return result;
} }),
Object.freeze({ id: 'M07-return-copy', witness: '02-return-identity', fill(o, v, ...b) {
nativeFill(o, v, ...b);
return Array.isArray(o) ? o.slice() : { ...o };
} }),
Object.freeze({ id: 'M08-array-only', witness: '28-generic-string-length', fill(o, v, ...b) {
if (!Array.isArray(o)) throw new TypeError('teaching mutant');
return nativeFill(o, v, ...b);
} }),
Object.freeze({ id: 'M09-swallow-failure', witness: '33-partial-write', fill(o, v, ...b) {
try { return nativeFill(o, v, ...b); }
catch { return o; }
} }),
Object.freeze({ id: 'M10-reverse-writes', witness: '33-partial-write', fill(o, v, ...b) {
// Narrow mutant: reverse only default-range writes on actual arrays.
if (Array.isArray(o) && b.length === 0) {
for (let i = o.length - 1; i >= 0; i -= 1) {
if (!Reflect.set(o, String(i), v)) throw new TypeError('teaching mutant');
}
return o;
}
return nativeFill(o, v, ...b);
} })
]);
function observe(testCase, fill) {
try { return { kind: 'return', value: testCase.run(fill) }; }
catch (error) { return { kind: 'throw', name: error.name }; }
}
function run() {
for (const item of cases) {
assert.deepStrictEqual(item.run(nativeFill), item.expected, item.id);
}
console.log(`PASS native ${cases.length}/${cases.length}`);
const witnesses = [];
for (const mutant of mutants) {
const item = cases.find(c => c.id === mutant.witness);
assert.ok(item, mutant.id);
const expected = { kind: 'return', value: item.expected };
const actual = observe(item, mutant.fill);
assert.notDeepStrictEqual(actual, expected, `${mutant.id} survived`);
const failedCases = cases.filter(c => {
const observed = observe(c, mutant.fill);
try {
assert.deepStrictEqual(observed, { kind: 'return', value: c.expected });
return false;
} catch { return true; }
}).map(c => c.id);
assert.ok(failedCases.includes(item.id));
witnesses.push({ mutant: mutant.id, case: item.id, expected, actual, failedCases });
console.log(`KILL ${mutant.id} witness=${item.id}`);
}
console.log(`PASS mutants ${mutants.length}/${mutants.length}`);
if (process.argv.includes('--witnesses')) {
fs.writeFileSync(path.join(__dirname, 'witnesses.json'),
JSON.stringify(witnesses, null, 2) + '\n');
}
}
if (require.main === module) run();
module.exports = { cases, mutants, nativeFill, observe };运行 node fill-lab.cjs,预期 stdout 如下,保存为 expected.txt。运行 node fill-lab.cjs --witnesses 还会在同目录生成 witnesses.json,记录每个指定反例的正确结果、错误结果以及该变体不通过的案例编号。
PASS native 40/40 KILL M01-clone-each witness=03-object-alias KILL M02-inclusive-end witness=09-half-open KILL M03-negative-as-zero witness=11-negative-start KILL M04-floor-fractions witness=23-negative-fractions KILL M05-nan-end-default witness=21-nan-end KILL M06-preserve-holes witness=06-fill-all-holes KILL M07-return-copy witness=02-return-identity KILL M08-array-only witness=28-generic-string-length KILL M09-swallow-failure witness=33-partial-write KILL M10-reverse-writes witness=33-partial-write PASS mutants 10/10
例如,M01 的反例会让对象身份判断失败;M02 会多改终点那个位置;M09 虽然同样留下部分修改,但错误返回值从 TypeError 变成 null;M10 则先修改索引 2,失败后留下 [0, 1, 9]。这些差异分别对应不同误解,不靠同一个布尔断言凑数。
六、复制后的文本也要校验
把前面的 example.cjs、example.expected.json、fill-lab.cjs、expected.txt 和下面的 verify.cjs 放在同一目录。运行 node verify.cjs,它会调用当前 Node 可执行文件,在普通与 --use-strict 两种方式下分别运行两个程序,并比较 stdout。
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
// Only ONE optional final LF is ignored. Never trim spaces or blank lines.
const optionalFinalLF = text => text.endsWith('\n') ? text.slice(0, -1) : text;
for (const flags of [[], ['--use-strict']]) {
for (const [script, golden] of [
['example.cjs', 'example.expected.json'],
['fill-lab.cjs', 'expected.txt']
]) {
const result = spawnSync(process.execPath, [...flags, script], {
cwd: __dirname, encoding: 'utf8'
});
assert.ifError(result.error);
assert.equal(result.status, 0, result.stderr);
assert.equal(result.signal, null);
assert.equal(result.stderr, '');
const expected = fs.readFileSync(path.join(__dirname, golden), 'utf8');
assert.equal(optionalFinalLF(result.stdout), optionalFinalLF(expected),
`${flags.join(' ') || 'ordinary'} ${script}`);
}
}
console.log('PASS stdout oracle: 2 programs x 2 modes');校验成功只输出一行:PASS stdout oracle: 2 programs x 2 modes。比较只允许一个可选的末尾 LF,不使用 trim,不吞掉行首、行尾空格或额外空行。example.expected.json 在这里按文本比较,不是解析 JSON 后忽略排版差异。
本次实际环境为 Node.js v24.19.0:40/40 原生行为案例通过;10/10 故意错误变体被各自指定反例检出;两个程序在两种方式下的 stdout 均符合固定预期。另按逆序和正序重跑案例,检查了输入独立性与冻结预期未改变。结果说明这些明确案例被覆盖,不代表通过完整 ECMAScript 一致性测试,也不提供性能结论或跨引擎错误文案保证。
结语:先确认你想复制的是值,还是创建新对象
填充统一数字、布尔值或有意共享的对象时,fill 很直接。每个位置需要独立状态,就让每次创建动作真正发生;范围处理要区分 NaN 与 undefined;遇到写入失败,则检查已经改变了哪些索引。把这三件事说清楚,比记住一串初始化写法更有用。
来源核验:北京时间 2026 年 10 月 22 日。本文引用 MDN 官方文档与 TC39 的持续更新工作草案;草案页面显示的“ECMAScript 2027”是该工作草案标题,不表示本文宣称 2027 正式标准已经发布。文中代码、固定预期与实验分析为本篇独立编写。


