JavaScript Array.reduce 与 reduceRight:初始值、稀疏槽位和访问方向
把一组明细累计为一个结果时,Array.reduce 很合适。但它的边界并不等于“从第 0 项开始循环”:初始值是否真正传入、某个索引是否存在,以及遍历从哪一侧开始,都会改变回调次数和结果。本文用同一套可运行实验说明 reduce 与 reduceRight,重点放在写封装和排查数据问题时最容易忽略的地方。
配图为独立模型生成的概念示意图,不是运行截图。两条箭头表示访问方向,空框象征缺失槽位;它不逐步模拟任何一个测试的调用轨迹。
一 先确定起点 再看回调
回调参数依次是 accumulator、currentValue、currentIndex、source。accumulator 来自上一次回调的返回值;source 是本次调用的接收对象,不是一个新副本。reduce 按索引升序访问,reduceRight 按降序访问。两者都没有 thisArg 参数。本文 G30 使用函数内显式严格模式,验证回调的 this 是 undefined,并检查四个参数。接口说明见 MDN reduce 文档。
对密集数组 [4, 7, 2],G01 传入初始值 10 并求和,三次回调收到的 [累加器, 当前值, 原索引] 为:
[[10,4,0],[14,7,1],[21,2,2]] 最终结果:23
G02 省略初始值,同一数组的 4 先成为累加器,回调只收到 [4, 7, 1] 和 [11, 2, 2],结果为 13。把 reduceRight 理解成“交换回调的两个值”会出错:G04 省略初始值并做减法,起点是最右侧的 2,计算过程是 (2 - 7) - 4,结果 -9;索引仍然是原数组的 1、0,不会重新从 0 编号。方向说明见 MDN reduceRight 文档。
二 省略初始值 不等于传入 undefined
这里判断的是实参有没有传入,不是该值是否为 undefined。省略初始值时,要沿遍历方向寻找第一个存在的索引,把它的值作为累加器;显式传入 undefined 时,累加器已经给定,首个存在的索引就需要调用回调。这一分支可对照 ECMAScript reduce 算法的 initialValue 分支。
G05:[5] 显式传 undefined,回调执行一次,收到 undefined、5、0。示例把结果写成字符串 "undefined:5",便于观察。
G06:[5] 省略初始值,直接返回 5,回调一次也不执行。不要把必须执行的校验只放进这种回调。
G07 与 G10:空数组、长度为 3 但全部是空槽的数组,在没有初始值时都抛 TypeError。这里假定原型链也没有可访问的对应索引。
G08、G09 与 G11:没有可访问元素但传了初始值,就直接返回该初始值,包含 undefined 或同一个对象引用,回调次数为 0。
G31:即便数组为空且有初始值,回调仍必须可调用。把 null 当回调不会因为“反正不用执行”就合法。
因此,若封装函数需要原样保留省略语义,就不能随手给 seed 写默认值 0,也不能用 seed === undefined 判定用户没传。下方 trace 用剩余参数 ...seed 保留了实参数量;W01、W02 专门证明两种错误封装会改变空输入的行为。
三 空槽与 undefined 不是同一回事
G12 使用 [, 8, , 3, ,]。它的长度是 5,但自有元素只在索引 1、3。省略初始值时,reduce 用 8 起步,仅在索引 3 回调一次;reduceRight 用 3 起步,仅在索引 1 回调一次。G14 传入 0 后,两侧都会回调两次,但顺序相反。
G15 换成 [undefined, , 4]。索引 0 的值虽然是 undefined,属性却存在,因此会被访问;索引 1 才是真正缺失。W03 中先用展开语法制作密集数组,再调用 reduce,会把原本跳过的空槽变成值为 undefined 的位置,并增加回调。这种预处理不是语义透明的替代。
“跳过空槽”还有一个常被省略的前提:对应索引不能在原型链上存在。规范在访问前使用 HasProperty,而不是只检查自有属性。本文 G16 给单个数组设置专用原型,该原型上有不可枚举的索引 1,值为 9。对 [2, , 4] 的求和是 15,不是 6。G17 的数组没有任何自有元素,却能用唯一的继承索引值 9 直接返回且不回调。参见 ECMAScript reduceRight 的 HasProperty 步骤。
这些实验只修改新建数组的局部原型,不修改 Array.prototype 或 Object.prototype。业务代码也不应为了验证一个边界而污染共享原型。
四 长度先确定 元素到访问时再读取
捕获长度不等于拍下所有元素的快照。G18 到 G26 使用小数组,在一次回调里做一次有限变更,结果如下;这些是实验观察,与 reduce 的遍历范围与逐项取值步骤一致。
删除尚未访问的索引:左向遍历 [2, 5, 7] 时,在索引 0 删除索引 2,只访问 0、1,结果 7。右向遍历时在索引 2 删除索引 0,只访问 2、1,结果 12。此处没有继承索引补位。
追加到原长度之外:对 [2, 5] 在第一次回调追加 7,两种方向的结果仍为 7,数组长度最终为 3,但新索引 2 不会被回调访问。
改写尚未访问的值:左向把末项改为 30,结果为 37;右向把首项改为 30,结果为 42。回调收到的是到访时的值。
填上尚未访问的空槽:对 [2, , 7] 在首次回调把索引 1 改为 5,两种方向都会访问这个新出现的范围内索引,结果 14。
删除当前项不会收回已传入的 currentValue。G25 删除索引 0 后,当前值 2 仍参与计算,结果 7。
把普通数组 length 缩为 1 会删除尾部自有元素。G26 从 [2, 5, 7] 读完首项后缩短数组,后续索引不再存在,最终结果为 2。
这些变更用于解释语义,不是建议在累计时随意修改源数组。实际需要修改数据结构、提前退出或者执行复杂副作用时,明确的循环往往更便于检查。
五 类数组也能调用 但仍按索引工作
G27 对 {0: 3, 2: 8, length: 3} 使用 Array.prototype.reduce.call,初始值为 1,结果 12,访问索引为 0、2;reduceRight 的顺序为 2、0。G28 将 length 写为 2.9,索引 2 不进入范围;G32 用 getter 验证长度读取一次。G29 借用方法处理字符串 "dog",得到 "dog" 与 "god",仅用基本拉丁字母展示方向,不把这个例子当成通用的 Unicode 字符反转方案。
这些方法不要求接收对象是真数组。此处“通用”指依赖长度和索引属性,不代表本文覆盖了所有代理陷阱、getter 副作用或特殊对象。参见 MDN 的非数组对象调用说明。
六 一个合适的累计场景
下面把一组已知有效的示例明细汇总成一个对象。保存为 receipt.cjs,运行 node receipt.cjs 即可。数量和单价都是本例的小整数;生产代码仍应明确输入类型、单位、范围与安全整数边界。
'use strict';
const assert = require('node:assert/strict');
const rows = [
{ qty: 2, unitCents: 300 },
{ qty: 1, unitCents: 1500 },
{ qty: 3, unitCents: 600 }
];
const seed = { units: 0, cents: 0 };
const result = rows.reduce((acc, row) => {
acc.units += row.qty;
acc.cents += row.qty * row.unitCents;
return acc;
}, seed);
// 与冻结预期 G34 相同,检查不受 NODE_ENV 影响。
assert.deepEqual({ same: result === seed, result },
{ same: true, result: { units: 6, cents: 3900 } });
console.log(JSON.stringify(result));输出:
{"units":6,"cents":3900}这个例子有意原地更新自己创建的累加器,G34 会检查结果就是该 seed 对象。关键在于每次都返回 acc。G35 展示漏写 return 后,下一次收到的 accumulator 会成为 undefined。G36 则证明回调返回 false 不会终止遍历;需要短路时不要把 reduce 当作 some 或 every 使用。若异常抛出,G33 验证后续索引不再被访问,原异常向外传播。
七 完整自检文件 36 组边界与 8 个错误封装
把下一段完整保存为 reduce-lab.cjs。它只依赖 Node.js 内置模块,预期值直接写在文件里,不需要下载测试框架、安装依赖或读取单独的数据文件。使用 assert/strict 的检查始终启用,不依赖 NODE_ENV。输出中的字符串 "undefined" 是日志用的显示标记;G09、G35 另有对真实 undefined 的直接检查。
分组导航:G01–G06 是起点与方向,G07–G11 是空输入,G12–G17 是槽位与继承,G18–G26 是变更,G27–G32 是类数组与调用约定,G33–G36 是异常、对象累计、返回值和不短路。W01–W08 逐一检查默认 0、混淆 undefined、展开空槽、只看自有属性、反转后再 reduce、提前复制值、动态读取长度和遇假值退出这八种错误。
// 本文件故意不写顶层 use strict,以验证普通 CommonJS 模式。
// 严格模式由下文 strict-runner.cjs 显式建立,并在本文件内探测。
const assert = require('node:assert/strict');
const { isDeepStrictEqual } = require('node:util');
const strictProbe = (function () { return this; })() === undefined;
const expectedStrict = typeof REDUCE_STRICT_WRAPPED === 'boolean'
? REDUCE_STRICT_WRAPPED : false;
assert.equal(strictProbe, expectedStrict, '严格模式探针不符合运行方式');
// 在行为执行前冻结的字面量预期,不调用被测方法生成答案。
const EXPECTED = {
"groups": {
"G01": {"value":23,"calls":[[10,4,0],[14,7,1],[21,2,2]]},
"G02": {"value":13,"calls":[[4,7,1],[11,2,2]]},
"G03": {"value":7,"calls":[[20,2,2],[18,7,1],[11,4,0]]},
"G04": {"value":-9,"calls":[[2,7,1],[-5,4,0]]},
"G05": {"value":"undefined:5","calls":[["undefined",5,0]]},
"G06": [5,5,0],
"G07": ["TypeError","TypeError"],
"G08": [true,true,0],
"G09": ["undefined","undefined",0],
"G10": ["TypeError","TypeError"],
"G11": [9,9,0],
"G12": {"value":11,"calls":[[8,3,3]]},
"G13": {"value":11,"calls":[[3,8,1]]},
"G14": [{"value":11,"calls":[[0,8,1],[8,3,3]]},{"value":11,"calls":[[0,3,3],[3,8,1]]}],
"G15": [[[0,"undefined"],[2,"number"]],[[2,"number"],[0,"undefined"]]],
"G16": {"left":{"value":15,"calls":[[0,2,0],[2,9,1],[11,4,2]]},"right":{"value":15,"calls":[[0,4,2],[4,9,1],[13,2,0]]},"own1":false},
"G17": [9,9,0],
"G18": {"value":7,"indices":[0,1],"length":3,"own0":true,"own2":false},
"G19": {"value":12,"indices":[2,1],"length":3,"own0":false,"own2":true},
"G20": {"value":7,"indices":[0,1],"length":3,"own0":true,"own2":true},
"G21": {"value":7,"indices":[1,0],"length":3,"own0":true,"own2":true},
"G22": {"value":37,"indices":[0,1,2],"length":3,"own0":true,"own2":true},
"G23": {"value":42,"indices":[2,1,0],"length":3,"own0":true,"own2":true},
"G24": [{"value":14,"indices":[0,1,2],"length":3,"own0":true,"own2":true},{"value":14,"indices":[2,1,0],"length":3,"own0":true,"own2":true}],
"G25": {"value":7,"indices":[0,1],"length":2,"own0":false,"own2":false},
"G26": {"value":2,"indices":[0],"length":1,"own0":true,"own2":false},
"G27": [{"value":12,"calls":[[1,3,0],[4,8,2]]},{"value":12,"calls":[[1,8,2],[9,3,0]]}],
"G28": [11,11],
"G29": ["dog","god"],
"G30": {"value":14,"calls":[[4,0,true,4,true],[9,1,true,4,true]]},
"G31": ["TypeError","TypeError"],
"G32": [{"value":14,"reads":1},{"value":14,"reads":1}],
"G33": [[true,[0,1]],[true,[2,1]]],
"G34": {"same":true,"result":{"units":6,"cents":3900}},
"G35": {"value":"undefined","seen":["number","undefined"]},
"G36": {"value":false,"indices":[0,1,2]}
},
"witnesses": {
"W01": {"native":"TypeError","wrong":0},
"W02": {"native":"undefined","wrong":"TypeError"},
"W03": {"native":[[1,"number"]],"wrong":[[0,"undefined"],[1,"number"]]},
"W04": {"native":15,"wrong":6},
"W05": {"native":"2:7;1:5;0:2;","wrong":"0:7;1:5;2:2;"},
"W06": {"native":37,"wrong":14},
"W07": {"native":7,"wrong":14},
"W08": {"native":{"value":false,"indices":[0,1,2]},"wrong":{"value":false,"indices":[0,1]}}
}
};
const modes = ['reduce', 'reduceRight'];
const add = (a, b) => a + b;
const show = value => value === undefined ? 'undefined' : value;
function outcome(fn) {
try { return show(fn()); } catch (error) { return error.name; }
}
function trace(array, method, reducer = add, ...seed) {
const calls = [];
const value = Array.prototype[method].call(array, (acc, item, index, source) => {
assert.equal(source, array, '回调必须收到原接收对象');
calls.push([show(acc), item, index]);
return reducer(acc, item);
}, ...seed);
return { value: show(value), calls };
}
function inherited(array) {
const prototype = Object.create(Array.prototype);
Object.defineProperty(prototype, '1', { value: 9, configurable: true });
Object.setPrototypeOf(array, prototype);
return array;
}
function mutate(method, array, action) {
const indices = [];
const value = array[method]((acc, item, index, source) => {
indices.push(index);
action(source, index);
return acc + item;
}, 0);
return { value, indices, length: array.length,
own0: Object.hasOwn(array, 0), own2: Object.hasOwn(array, 2) };
}
const cases = {
G01: () => trace([4, 7, 2], 'reduce', add, 10),
G02: () => trace([4, 7, 2], 'reduce'),
G03: () => trace([4, 7, 2], 'reduceRight', (a, b) => a - b, 20),
G04: () => trace([4, 7, 2], 'reduceRight', (a, b) => a - b),
G05: () => trace([5], 'reduce', (a, b) => `${typeof a}:${b}`, undefined),
G06: () => {
let calls = 0;
const values = modes.map(m => [5][m](() => { calls++; throw Error('不应调用'); }));
return [...values, calls];
},
G07: () => modes.map(m => outcome(() => [][m](add))),
G08: () => {
let calls = 0; const seed = { count: 0 };
const same = modes.map(m => [][m](() => { calls++; }, seed) === seed);
return [...same, calls];
},
G09: () => {
let calls = 0;
const values = modes.map(m => {
const value = [][m](() => { calls++; }, undefined);
assert.equal(value, undefined); return show(value);
});
return [...values, calls];
},
G10: () => modes.map(m => outcome(() => new Array(3)[m](add))),
G11: () => {
let calls = 0;
const values = modes.map(m => new Array(3)[m](() => { calls++; }, 9));
return [...values, calls];
},
G12: () => trace([, 8, , 3, ,], 'reduce'),
G13: () => trace([, 8, , 3, ,], 'reduceRight'),
G14: () => modes.map(m => trace([, 8, , 3, ,], m, add, 0)),
G15: () => modes.map(m => [undefined, , 4][m]((acc, x, i) => {
acc.push([i, typeof x]); return acc;
}, [])),
G16: () => {
const array = inherited([2, , 4]);
return { left: trace(array, 'reduce', add, 0),
right: trace(array, 'reduceRight', add, 0), own1: Object.hasOwn(array, 1) };
},
G17: () => {
let calls = 0;
const array = inherited(new Array(3));
const values = modes.map(m => array[m](() => { calls++; }));
return [...values, calls];
},
G18: () => mutate('reduce', [2, 5, 7], (a, i) => { if (i === 0) delete a[2]; }),
G19: () => mutate('reduceRight', [2, 5, 7], (a, i) => { if (i === 2) delete a[0]; }),
G20: () => mutate('reduce', [2, 5], (a, i) => { if (i === 0) a.push(7); }),
G21: () => mutate('reduceRight', [2, 5], (a, i) => { if (i === 1) a.push(7); }),
G22: () => mutate('reduce', [2, 5, 7], (a, i) => { if (i === 0) a[2] = 30; }),
G23: () => mutate('reduceRight', [2, 5, 7], (a, i) => { if (i === 2) a[0] = 30; }),
G24: () => modes.map(m => mutate(m, [2, , 7], (a, i) => {
if (i === (m === 'reduce' ? 0 : 2)) a[1] = 5;
})),
G25: () => mutate('reduce', [2, 5], (a, i) => { if (i === 0) delete a[0]; }),
G26: () => mutate('reduce', [2, 5, 7], (a, i) => { if (i === 0) a.length = 1; }),
G27: () => modes.map(m => trace({ 0: 3, 2: 8, length: 3 }, m, add, 1)),
G28: () => modes.map(m => Array.prototype[m].call(
{ 0: 3, 1: 8, 2: 100, length: 2.9 }, add, 0)),
G29: () => modes.map(m => Array.prototype[m].call('dog', add, '')),
G30: () => {
const array = [4, 9]; const calls = [];
const value = array.reduce(function (acc, x, i, source) {
'use strict';
calls.push([x, i, source === array, arguments.length, this === undefined]);
return acc + x;
}, 1);
return { value, calls };
},
G31: () => modes.map(m => outcome(() => [][m](null, 1))),
G32: () => modes.map(m => {
let reads = 0;
const arrayLike = { 0: 2, 1: 5, 2: 7, get length() { reads++; return 3; } };
const value = Array.prototype[m].call(arrayLike, add, 0);
return { value, reads };
}),
G33: () => modes.map(m => {
const marker = Error('marker'); const indices = [];
try {
[2, 5, 7][m]((acc, x, i) => {
indices.push(i); if (i === 1) throw marker; return acc + x;
}, 0);
throw Error('应当抛错');
} catch (error) { return [error === marker, indices]; }
}),
G34: () => {
const rows = [{ qty: 2, unitCents: 300 }, { qty: 1, unitCents: 1500 },
{ qty: 3, unitCents: 600 }];
const seed = { units: 0, cents: 0 };
const result = rows.reduce((acc, row) => {
acc.units += row.qty; acc.cents += row.qty * row.unitCents; return acc;
}, seed);
return { same: result === seed, result };
},
G35: () => {
const seen = [];
const value = [3, 4].reduce(acc => { seen.push(typeof acc); }, 0);
assert.equal(value, undefined);
return { value: show(value), seen };
},
G36: () => {
const indices = [];
const value = [2, 5, 7].reduce((acc, x, i) => {
indices.push(i); return acc && x < 5;
}, true);
return { value, indices };
}
};
// 以下均为故意错误的封装,只作为反例,不是 polyfill。
const wrong = {
zeroSeed: (a, fn, seed = 0) => a.reduce(fn, seed),
undefinedMeansMissing: (a, fn, seed) => seed === undefined
? a.reduce(fn) : a.reduce(fn, seed),
densify: (a, fn, seed) => [...a].reduce(fn, seed),
ownOnly(a, fn, seed) {
let acc = seed;
for (let i = 0; i < a.length; i++) {
if (Object.hasOwn(a, i)) acc = fn(acc, a[i], i, a);
}
return acc;
},
reverseThenReduce: (a, fn, seed) => a.slice().reverse().reduce(fn, seed),
snapshot: (a, fn, seed) => Array.from(a).reduce(fn, seed),
liveLength(a, fn, seed) {
let acc = seed;
for (let i = 0; i < a.length; i++) {
if (i in a) acc = fn(acc, a[i], i, a);
}
return acc;
},
stopOnFalse(a, fn, seed) {
let acc = seed;
for (let i = 0; i < a.length; i++) {
if (i in a) { acc = fn(acc, a[i], i, a); if (!acc) break; }
}
return acc;
}
};
const native = (a, fn, ...seed) => a.reduce(fn, ...seed);
const collect = (acc, x, i) => { acc.push([i, typeof x]); return acc; };
function pendingValue(run) {
const a = [2, 5, 7];
return run(a, (acc, x, i) => { if (i === 0) a[2] = 30; return acc + x; }, 0);
}
function append(run) {
const a = [2, 5];
return run(a, (acc, x, i) => { if (i === 0) a.push(7); return acc + x; }, 0);
}
function falseReturn(run) {
const indices = [];
const value = run([2, 5, 7], (acc, x, i) => {
indices.push(i); return acc && x < 5;
}, true);
return { value, indices };
}
const witnesses = {
W01: () => ({ native: outcome(() => native([], add)),
wrong: outcome(() => wrong.zeroSeed([], add)) }),
W02: () => ({ native: outcome(() => native([], add, undefined)),
wrong: outcome(() => wrong.undefinedMeansMissing([], add, undefined)) }),
W03: () => ({ native: native([, 4], collect, []),
wrong: wrong.densify([, 4], collect, []) }),
W04: () => ({ native: native(inherited([2, , 4]), add, 0),
wrong: wrong.ownOnly(inherited([2, , 4]), add, 0) }),
W05: () => {
const fn = (acc, x, i) => acc + `${i}:${x};`;
return { native: [2, 5, 7].reduceRight(fn, ''),
wrong: wrong.reverseThenReduce([2, 5, 7], fn, '') };
},
W06: () => ({ native: pendingValue(native), wrong: pendingValue(wrong.snapshot) }),
W07: () => ({ native: append(native), wrong: append(wrong.liveLength) }),
W08: () => ({ native: falseReturn(native), wrong: falseReturn(wrong.stopOnFalse) })
};
const observed = { groups: {}, witnesses: {} };
assert.equal(Object.keys(cases).length, 36);
assert.equal(Object.keys(witnesses).length, 8);
for (const [id, run] of Object.entries(cases)) {
const actual = run();
assert.deepEqual(actual, EXPECTED.groups[id], id);
observed.groups[id] = actual;
}
for (const [id, run] of Object.entries(witnesses)) {
const actual = run();
assert.deepEqual(actual, EXPECTED.witnesses[id], id);
assert.equal(isDeepStrictEqual(actual.native, actual.wrong), false, `${id} 必须区分错误封装`);
observed.witnesses[id] = actual;
}
console.log(`PASS 36 groups + 8 wrong-wrapper witnesses; strict=${strictProbe}; runtime=${process.version}`);
if (process.argv.includes('--json')) console.log(JSON.stringify(observed, null, 2));普通 CommonJS 模式运行:node reduce-lab.cjs。若要看每组实际值,追加 --json。
为了验证真正的严格模式,再把下面的辅助文件保存为 strict-runner.cjs,与主文件放在同一目录,运行 node strict-runner.cjs。它把同一份本地测试源码放进带有显式 "use strict" 指令的 Function 函数体;主文件内部的 this 探针必须变为 true。这里不把命令行 --use-strict 当作 CommonJS 用户源码已处于严格模式的证据。
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const source = fs.readFileSync(path.join(__dirname, 'reduce-lab.cjs'), 'utf8');
// Function 的函数体显式包含严格模式指令,主脚本内部还会检查 this 探针。
new Function('require', 'process', 'REDUCE_STRICT_WRAPPED',
'"use strict";\n' + source)(require, process, true);本次在 Node.js v24.19.0 中运行的摘要,普通模式与显式严格模式各运行一次:
PASS 36 groups + 8 wrong-wrapper witnesses; strict=false; runtime=v24.19.0 PASS 36 groups + 8 wrong-wrapper witnesses; strict=true; runtime=v24.19.0
八 怎样理解这次验证
本次预期值先根据规则逐组推导并写成字面量,随后才执行被测行为。冻结时间为北京时间 2026 年 10 月 22 日 07:20:44;原始预期 JSON 的 SHA-256 为 49c357b97ba10b67c1dea626b7a6d2f2631bc71c81f5391d84cad7040dad28ce。两种模式均通过 36 组结果对照与 8 组错误封装区分,预期文件未在运行后改写。
这些是教学回归实验,不是完整的 ECMAScript 一致性测试,也没有进行性能基准或所有浏览器版本测试。结论限于文中具体输入和所说明的规范规则;不覆盖 Proxy 的完整操作顺序、跨 realm、TypedArray 特有行为或异步任务调度。错误封装只是反例,不能用于生产,也不是完整 polyfill。
选择 reduce 的理由应当是“一个清晰的累加器能表达这项工作”。先明确空输入要返回什么,再明确是否允许稀疏槽位和继承属性;最后确认方向是否影响结果、回调是否始终返回累加器。做到这几项,比把每个循环改写成 reduce 更有价值。


