JavaScript reduce 初值不是可有可无:12 组实验看懂 undefined、空槽与 Map 分组

10-21 10阅读

把 reduce 的第二个参数删掉,和把它写成 undefined,是同一件事吗?不是。更容易被忽略的是:数组长度大于零,也不代表一定能在省略初值时完成归约;长度为 5 的数组,回调甚至可能一次也不执行。

本文用 12 组可直接运行的断言,把“初始累加器从哪里来”和“哪些索引会进入回调”拆开观察。所有示例均为本文编写的独立实验,已在 Node.js v24.19.0 实测;不需要安装依赖,不发起网络请求。

JavaScript reduce 初值不是可有可无:12 组实验看懂 undefined、空槽与 Map 分组

配图为独立模型生成的概念示意,不是软件截图;箭头表示存在的元素参与结果形成,不表示每个箭头都对应一次回调。上排第一个存在的元素直接提供种子,下排的种子由参数提供。空框表示示意性的空槽,精确行为以代码断言为准。

一、先判断参数是否提供,再判断索引是否存在

TC39 的 reduce 算法把“是否提供 initialValue”作为分支条件,而不是判断它是否等于 undefined:

  • 提供初值:直接将该值作为累加器,然后从索引 0 开始寻找可处理的属性。

  • 省略初值:先寻找第一个存在的索引属性,将其值作为累加器;这个元素不进入回调,后续元素才进入。

  • 找不到可用元素且没有初值:抛出 TypeError。对于未被原型链索引影响的普通数组,空数组与全空槽数组都属于这一情形。

第 1 组把同一个加法回调应用到 [2, 3, 4]:省略初值得到 9,索引为 [1,2];显式传 0 也得到 9,但索引变成 [0,1,2];显式传 undefined 则从 undefined + 2 开始,结果是 NaN。这里的 NaN 来自加法运算,不是 reduce 自动把 undefined 当成了错误。

实验中的 run 使用剩余参数与展开调用保留“零个初值实参”和“一个值为 undefined 的实参”的区别。若封装函数无条件把形参 initial 传下去,调用方没有提供初值时,也可能被封装成“明确提供 undefined”,从而改变语义。

二、空槽、undefined 与只有一个元素不能混为一谈

第 2 组验证 [] 和 new Array(3):省略初值都抛错;传 0 都返回 0;传 undefined 都返回 undefined,而且回调次数都是 0。这里特意同时验证 [].reduce(null, 0) 仍然抛 TypeError,不能把“无元素”理解成“连回调参数是否合法也不用检查”。

第 3 组只在长度为 5 的数组的索引 3 放入对象。省略初值后,返回的就是那个对象本身,回调一次也没有执行。[undefined] 也具有一个真实存在的索引属性,因此同样直接返回 undefined。准确条件是“只有一个存在的索引属性”,不是“只有一个非 undefined 值”。

第 4 组的 [undefined, , 3] 则明确访问索引 0 与 2,跳过空槽 1。我们把值转成字符串后记录,避免 JSON.stringify 把数组中的 undefined 显示为 null,从而掩盖实验对象。MDN 也明确区分了稀疏数组的空槽与 undefined。

三、“存在”包含原型链,不等于 Object.hasOwn

reduce 使用 HasProperty 判断索引是否存在。这个操作既考虑自身属性,也考虑继承属性,见 TC39 HasProperty 定义。因此,说“它只处理数组自身有值的位置”并不严谨。

第 5 组创建专用的局部原型,给它放入索引 1 的值 20;数组自身仅在索引 2 放入 30。索引 1 的 Object.hasOwn 为 false,但 in 运算结果为 true。提供 0 时,回调索引是 [1,2];省略初值时,继承到的 20 先充当种子,回调只访问索引 2。两种方式的和都是 50。

这是隔离的语义实验,不是生产建议。代码不修改 Array.prototype,并在 finally 中恢复该数组的原型。业务代码不应依赖为数组设置特殊原型来组织数据。删除一个自身索引后,如果原型链还有同名属性,它也可能被读取,所以“删除就一定跳过”同样需要前提。

四、长度快照不是值快照

第 7 至第 9 组把三种变化分开测试。这里的变化只是实验手段;实际业务通常更容易维护的做法,是归约时不再修改输入数组。

  • 追加与改值:初始数组 [1,2,3] 在第一次回调中追加 4,并把索引 1 改成 20。结果访问 [1,20,3],不访问新追加的索引 3,总和为 24。

  • 填洞与删除:在尚未访问的位置填入值可以被看到;删除尚未访问且无继承替代的索引则会跳过。本例最终访问索引 [0,1,3]。

  • 缩短真实数组:将 length 改为 1 会删除本例后面的数组元素,所以只回调索引 0。这不是 reduce 在每轮重新读取 length。

  • 类数组对象:第 9 组借用 Array.prototype.reduce.call,length getter 仅被读取一次,初始界限外的索引 3 不参与求和。

这些日志说明:开始时确定的是遍历上界,属性是否存在以及它当时的值,要等到相应索引被处理时才确定。不要把它当成“提前复制了一份数组内容”。上述行为对应 reduce 规范中的 length、HasProperty 与 Get 步骤。

五、对象初值不会被克隆,异常也不会自动回滚

第 10 组每轮都返回同一个 seed 对象,最终 result === seed,seed.total 已被改为 5。空数组配这个初值时也返回同一个对象。若只改对象却漏写 return,回调的返回值就是 undefined;单元素实验会直接把 undefined 作为最终结果,而不是“自动帮你继续使用原对象”。

第 12 组让第二次回调抛出指定的 Error,并验证捕获到的就是该对象。后续索引不会继续处理,但此前已经写入 seed 的 total = 1 不会撤销。类数组 getter 抛错时也会中断,后面的 getter 没有被读取。规范算法中的问号表示对异常完成的传播,可结合 TC39 的异常传播记法阅读。reduce 不是事务机制。

如果归约中需要写入共享状态,应先想清楚失败后如何处理部分结果。对“必须全部成功才生效”的业务,优先在局部结果上完成验证,再由调用方决定提交,而不是期待 reduce 替你撤销副作用。

六、动态分组键用 Map,不把原型属性当成数据桶

本文给出的 groupByKind 约定输入为记录数组,每条记录带 kind 字段。它每次创建新的 Map,通过 has、set、get 管理分组,不把动态键写成普通对象属性。

第 11 组专门使用 __proto__、constructor 和 toString 三种键,得到三个普通分组;重复的 __proto__ 记录进入同一个桶。Map 的键值存储与对象属性命名空间不同,参考 MDN 对 Map 与 Object 的比较。注意,正确用法是 groups.set(key, value),不是 groups[key] = value。

这个选择解决的是分组键与对象原型属性碰撞的问题,不等于对任意输入完成了安全校验。还应按业务验证记录结构与数量。代码保留原记录的引用,没有深拷贝:修改桶里某条记录的字段,也会影响原数组中的同一个对象。若需要隔离,必须另行确定复制策略。

七、完整实验:复制一个文件即可运行

将下面完整代码保存为 complete.cjs,在终端运行 node complete.cjs。文件首行显式使用 'use strict',第 6 组再验证普通函数回调的 this 为 undefined,以及四个回调参数。严格模式的开启方式见 MDN 严格模式说明。这里不依赖启动标志来猜测 CommonJS 文件是否处于严格模式。

代码只依赖 Node 内置的 node:assert/strict。每组先执行断言,再打印摘要;错误会使程序停止,不会把失败结果包装成 PASS。

'use strict';

const assert = require('node:assert/strict');
let passed = 0;
function group(name, test) {
  const detail = test();
  passed += 1;
  console.log(`${String(passed).padStart(2, '0')} ${name}: ${detail}`);
}
console.log(`Node ${process.version}`);

group('omitted-vs-undefined', () => {
  const input = [2, 3, 4];
  const traces = [];
  function run(...initial) {
    const indices = [];
    const result = input.reduce((acc, value, index) => {
      indices.push(index);
      return acc + value;
    }, ...initial);
    traces.push(indices);
    return result;
  }
  assert.equal(run(), 9);
  assert.equal(run(0), 9);
  assert.ok(Number.isNaN(run(undefined)));
  assert.deepEqual(traces, [[1, 2], [0, 1, 2], [0, 1, 2]]);
  return '9 [1,2] | 9 [0,1,2] | NaN [0,1,2]';
});

group('empty-and-holes', () => {
  let calls = 0;
  const add = (acc, value) => { calls += 1; return acc + value; };
  for (const input of [[], new Array(3)]) {
    assert.throws(() => input.reduce(add), TypeError);
    assert.equal(input.reduce(add, 0), 0);
    assert.equal(input.reduce(add, undefined), undefined);
  }
  assert.equal(calls, 0);
  assert.throws(() => [].reduce(null, 0), TypeError);
  return 'both: omitted throws; 0 => 0; undefined => undefined; calls=0';
});

group('one-present-value', () => {
  const item = { id: 'only' };
  const input = new Array(5);
  input[3] = item;
  let calls = 0;
  const callback = () => { calls += 1; return 'unexpected'; };
  assert.equal(input.reduce(callback), item);
  assert.equal([undefined].reduce(callback), undefined);
  assert.equal(calls, 0);
  return 'same object=true; [undefined] => undefined; calls=0';
});

group('holes-vs-undefined', () => {
  const indices = [];
  const values = [undefined, , 3].reduce((acc, value, index) => {
    indices.push(index);
    acc.push(String(value));
    return acc;
  }, []);
  assert.deepEqual(indices, [0, 2]);
  assert.deepEqual(values, ['undefined', '3']);
  assert.equal([1, , 3].reduce((acc, value) => acc + value, 0), 4);
  assert.ok(Number.isNaN([1, undefined, 3].reduce((acc, value) => acc + value, 0)));
  return 'indices=[0,2]; values=[undefined,3]; hole sum=4; undefined sum=NaN';
});

group('inherited-index', () => {
  // Isolated test only: do not modify Array.prototype.
  const input = new Array(3);
  input[2] = 30;
  const localPrototype = Object.create(Array.prototype);
  localPrototype[1] = 20;
  Object.setPrototypeOf(input, localPrototype);
  try {
    assert.equal(Object.hasOwn(input, 1), false);
    assert.equal(1 in input, true);
    const withInitial = [];
    const withoutInitial = [];
    assert.equal(input.reduce((acc, value, index) => {
      withInitial.push(index);
      return acc + value;
    }, 0), 50);
    assert.equal(input.reduce((acc, value, index) => {
      withoutInitial.push(index);
      return acc + value;
    }), 50);
    assert.deepEqual(withInitial, [1, 2]);
    assert.deepEqual(withoutInitial, [2]);
  } finally {
    Object.setPrototypeOf(input, Array.prototype);
  }
  return 'inherited 1 participates; initial indices=[1,2]; omitted indices=[2]; sum=50';
});

group('callback-contract', () => {
  const input = [7];
  let calls = 0;
  const result = input.reduce(function (acc, value, index, source) {
    calls += 1;
    assert.equal(this, undefined);
    assert.equal(arguments.length, 4);
    assert.equal(source, input);
    assert.deepEqual([acc, value, index], [10, 7, 0]);
    return acc + value;
  }, 10);
  assert.equal(result, 17);
  assert.equal(calls, 1);
  return 'argc=4; same source=true; strict this=undefined; result=17';
});

group('append-and-update', () => {
  const input = [1, 2, 3];
  const seen = [];
  const sum = input.reduce((acc, value, index, source) => {
    seen.push([index, value]);
    if (index === 0) {
      source.push(4);
      source[1] = 20;
    }
    return acc + value;
  }, 0);
  assert.equal(sum, 24);
  assert.deepEqual(seen, [[0, 1], [1, 20], [2, 3]]);
  assert.deepEqual(input, [1, 20, 3, 4]);
  return 'seen=[[0,1],[1,20],[2,3]]; sum=24; final length=4';
});

group('fill-delete-shrink', () => {
  const seen = [];
  const sum = [1, , 3, 4].reduce((acc, value, index, source) => {
    seen.push([index, value]);
    if (index === 0) {
      source[1] = 2;
      delete source[2];
    }
    return acc + value;
  }, 0);
  assert.equal(sum, 7);
  assert.deepEqual(seen, [[0, 1], [1, 2], [3, 4]]);
  const indices = [];
  const shrunk = [1, 2, 3].reduce((acc, value, index, source) => {
    indices.push(index);
    source.length = 1;
    return acc + value;
  }, 0);
  assert.equal(shrunk, 1);
  assert.deepEqual(indices, [0]);
  return 'fill/delete seen=[[0,1],[1,2],[3,4]]; sum=7; shrink indices=[0]';
});

group('array-like-length', () => {
  let reads = 0;
  const input = {
    0: 2, 1: 4, 2: 6, 3: 100,
    get length() { reads += 1; return reads === 1 ? 3 : 1; }
  };
  const sum = Array.prototype.reduce.call(input, (acc, value) => acc + value, 0);
  assert.equal(sum, 12);
  assert.equal(reads, 1);
  return 'length getter reads=1; index 3 excluded; sum=12';
});

group('accumulator-identity', () => {
  const seed = { total: 0 };
  const result = [2, 3].reduce((acc, value) => {
    assert.equal(acc, seed);
    acc.total += value;
    return acc;
  }, seed);
  assert.equal(result, seed);
  assert.equal(seed.total, 5);
  assert.equal([].reduce((acc) => acc, seed), seed);
  const missingReturnSeed = { total: 0 };
  const missingReturn = [2].reduce((acc, value) => {
    acc.total += value;
    // Deliberate negative test: no return statement.
  }, missingReturnSeed);
  assert.equal(missingReturn, undefined);
  assert.equal(missingReturnSeed.total, 2);
  return 'same seed=true; seed.total=5; missing return => undefined';
});

function groupByKind(rows) {
  return rows.reduce((groups, row) => {
    if (!groups.has(row.kind)) groups.set(row.kind, []);
    groups.get(row.kind).push(row);
    return groups;
  }, new Map());
}

group('safe-map-grouping', () => {
  const rows = [
    { kind: '__proto__', id: 1 },
    { kind: 'constructor', id: 2 },
    { kind: '__proto__', id: 3 },
    { kind: 'toString', id: 4 }
  ];
  const groups = groupByKind(rows);
  const summary = [...groups].map(([key, bucket]) => [key, bucket.map(row => row.id)]);
  assert.deepEqual(summary, [
    ['__proto__', [1, 3]], ['constructor', [2]], ['toString', [4]]
  ]);
  assert.equal(groups.get('__proto__')[0], rows[0]);
  assert.equal(Object.hasOwn(groups, '__proto__'), false);
  assert.equal(groupByKind([]).size, 0);
  assert.notEqual(groupByKind([]), groupByKind([]));
  return JSON.stringify(summary);
});

group('exception-propagation', () => {
  const callbackError = new Error('callback failure');
  const seen = [];
  const seed = { total: 0 };
  assert.throws(() => [1, 2, 3].reduce((acc, value, index) => {
    seen.push(index);
    if (index === 1) throw callbackError;
    acc.total += value;
    return acc;
  }, seed), error => error === callbackError);
  assert.deepEqual(seen, [0, 1]);
  assert.equal(seed.total, 1);
  const getterError = new Error('getter failure');
  let laterReads = 0;
  const source = {
    length: 3, 0: 1,
    get 1() { throw getterError; },
    get 2() { laterReads += 1; return 3; }
  };
  assert.throws(() => Array.prototype.reduce.call(source, (acc, value) => acc + value, 0),
    error => error === getterError);
  assert.equal(laterReads, 0);
  return 'same errors=true; callback indices=[0,1]; seed.total=1; later getter reads=0';
});

assert.equal(passed, 12);
console.log('PASS 12/12');

八、实测输出与使用检查清单

以下为 Node.js v24.19.0 的完整实测输出。其他 Node 版本的第一行会显示本机版本;其余日志应与下面一致。本实验未声称覆盖所有 JavaScript 引擎或所有 Proxy/getter 组合。

Node v24.19.0
01 omitted-vs-undefined: 9 [1,2] | 9 [0,1,2] | NaN [0,1,2]
02 empty-and-holes: both: omitted throws; 0 => 0; undefined => undefined; calls=0
03 one-present-value: same object=true; [undefined] => undefined; calls=0
04 holes-vs-undefined: indices=[0,2]; values=[undefined,3]; hole sum=4; undefined sum=NaN
05 inherited-index: inherited 1 participates; initial indices=[1,2]; omitted indices=[2]; sum=50
06 callback-contract: argc=4; same source=true; strict this=undefined; result=17
07 append-and-update: seen=[[0,1],[1,20],[2,3]]; sum=24; final length=4
08 fill-delete-shrink: fill/delete seen=[[0,1],[1,2],[3,4]]; sum=7; shrink indices=[0]
09 array-like-length: length getter reads=1; index 3 excluded; sum=12
10 accumulator-identity: same seed=true; seed.total=5; missing return => undefined
11 safe-map-grouping: [["__proto__",[1,3]],["constructor",[2]],["toString",[4]]]
12 exception-propagation: same errors=true; callback indices=[0,1]; seed.total=1; later getter reads=0
PASS 12/12

回到业务代码,可以按下面顺序检查:

  1. 初值是否明确?它是否表达空输入时业务真正需要的结果,而不只是为了避免 TypeError?

  2. 数据是否可能稀疏?不要用 length 推断实际回调次数,也不要用“值不为 undefined”判断索引存在。

  3. 是否误以为数组已经快照?回调里追加、删除、改值都会让阅读成本增加,最好避免这种设计。

  4. 累加器是否共享?明确选择局部可变对象或返回新值,所有分支都记得返回正确的累加器。

  5. 分组键是否来自动态输入?优先选择 Map 的键接口,并明确桶内记录是否共享引用。

  6. 异常出现后有没有部分副作用?把失败处理写在调用边界,不要假设自动回滚。

reduce 的关键不是把一段循环压成一行,而是让初值、访问范围、累加器所有权都清晰。若普通循环更容易表达这些约束,就使用普通循环;不要为了形式而隐藏控制流。

核验来源与范围

核验日期:2026 年 10 月 21 日(北京时间)。本文引用 TC39 当前在线算法作为语义依据,不将在线草案页的年份当作某个引擎的已实现版本或发布公告。代码、数据、断言与输出为本次独立实验。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。