JavaScript at() 的 36 个边界:负索引、空洞与 length 转换

10-22 4阅读

把列表最后一项写成 items.at(-1),通常比 items[items.length - 1] 更清楚。但负索引只是入口:索引要先转换,length 也要先转换;读取空洞可能走到原型链,越界返回 undefined 也不等于整个调用没有副作用。

本文围绕 Array.prototype.at 做一组可复现实验:36 个独立输入分别检查原生方法与教学模型,另外用 10 个故意写错的实现检验测试是否能抓住语义差异。测试环境是 Node.js v24.19.0,普通启动和 --use-strict 启动均实测。本文不声称完成全部 ECMAScript 一致性测试,也不把该模型当作可直接发布的 polyfill。

JavaScript at() 的 36 个边界:负索引、空洞与 length 转换
模型生成的概念示意图,非真实编辑器截图。四个位置对应 0 到 3,也对应 -4 到 -1;右侧独立方块表示名为 '-1' 的普通属性。

一、负索引和属性名 '-1' 分别在做什么

下面的小例子可以单独保存为 quick-demo.cjs。给数组添加 '-1' 属性不会把它变成“倒数第一项”,也不会增加数组长度。at(-1) 根据长度计算位置,方括号 tasks[-1] 则读取名为 '-1' 的属性。这一区别也见于 MDN 的 at() 说明。

const tasks = ['draft', 'review', 'publish'];
tasks['-1'] = 'note';
console.log(tasks.at(-1)); // publish
console.log(tasks[-1]);    // note
console.log(tasks.length); // 3
console.log(tasks.at(-0)); // draft
console.log(tasks.at(-0.9)); // draft
console.log(tasks.at(-1.9)); // publish

省略参数、传 undefined、NaN 或 -0,都会走到位置 0。有限小数先朝零截断,所以 -1.9 得到 -1,-0.9 则落在 0,而不是倒数第一项。不要把这一步换成 Math.floor:Math.floor(-1.9) 会得到 -2。下方测试还覆盖数字字符串 '-2';BigInt 与 Symbol 不是这里可以直接接受的索引,转换会抛出 TypeError。

二、先读长度,再转换索引,最后才读元素

ECMAScript 当前工作草案中的 Array.prototype.at 算法先取得对象和类数组长度,再求绝对位置,检查边界后才读取目标属性。具体的索引转换由 ToIntegerOrInfinity 与 ToAbsoluteIndex 定义。

  • 长度为 3 时,-3 对应位置 0;3 和 -4 已越界,不会读取对象上可能恰好存在的 '3' 或 '-1' 属性。

  • Infinity 与 -Infinity 索引越界。at 不做循环取模,也不会把越界索引压到首项或末项。

  • 越界前仍要读取 length 和转换 index。即使是空数组,索引对象的 valueOf 也可能执行或抛错。

  • 长度是在索引转换之前取得的。如果索引对象在 valueOf 中改变 length,后续位置计算仍使用先前取得的长度。这里只保存长度,不会快照元素值。

这也解释了“读取操作”的边界:at 自身没有向接收对象写元素,但用户定义的 getter、Proxy trap、类型转换方法可以有副作用。不要把“不主动写入”理解成纯函数保证。

三、返回 undefined 不能证明这个位置是空洞

没有自有元素的空洞、显式保存 undefined 的元素,以及越界读取,都可能返回 undefined。要区分前两者,需要额外观察 Object.hasOwn。另一方面,在有效范围内,at 使用普通属性读取;局部原型对象上若有同名数字属性或 getter,也能提供返回值。

实验只改变临时数组自身的原型链,没有修改 Array.prototype 或 Object.prototype。hole-without-prototype-value 将临时数组原型设为 null,排除继承值;hole-with-local-inheritance 则给另一个临时数组使用独立原型对象。两者都通过借用 Array.prototype.at 调用,因此不依赖临时数组能否从原型链找到 at 方法。

四、类数组 length 是独立的一道转换

at 可以借给带 length 与数字键的普通对象,不要求可迭代。LengthOfArrayLike 读取 length,再交给 ToLength 截断并限制到 0 至 2 的 53 次方减 1。它不是 length >>> 0 那样的 32 位转换。

因此 length 为字符串 '2.9' 的对象,末项位置是 1;负长度、缺失长度和 NaN 长度都使可访问范围为空。测试用一个只有少数属性的普通对象检验 Infinity 长度的上限,另一个检验超过 32 位的长度,绝不分配巨型数组或遍历这些长度。BigInt 长度会抛出 TypeError,而不是悄悄接受。

范围说明:本文的代码目标是 Array.prototype.at,不是 TypedArray.prototype.at,也不讨论它们的缓冲区约束。教学模型保留接收者检查与数值转换顺序,但没有安装到全局原型上。

五、完整实验:先固定答案,再执行实现

把下面六个文件按文件名保存到同一个空目录。加上前面的 quick-demo.cjs,共七个文件,无 npm 包、无网络请求、无隐藏数据依赖;仅使用 Node 内置模块。expected.cjs 与 expected-output.txt 在实现运行之前写定,之后保持哈希不变。输入场景在每次调用时新建对象,不共享上一次运行的可变状态。仅允许复制 expected-output.txt 时省略最后一个换行 LF;其他字符、空格与换行必须完全一致,不使用 trim 放宽检查。

测试不是用同一份实现给自己生成答案:原生方法和教学模型都要分别对照字面量预期。36 个场景检查返回值、属性所有权、异常名称、getter 次数和访问顺序。失败由显式 throw 报告;--use-strict 不是“关闭检查”的模式。

文件 1,固定预期:expected.cjs

// Frozen before the implementation. No calls to Array.prototype.at here.
module.exports = [
  ['negative-last', 'C'],
  ['positive-index', 'B'],
  ['negative-first', 'A'],
  ['literal-minus-one', ['C', 'side', 3]],
  ['omitted-index', 'A'],
  ['negative-zero', 'A'],
  ['nan-index', 'A'],
  ['positive-fraction', 'B'],
  ['negative-fraction', 'C'],
  ['negative-subunit', 'A'],
  ['numeric-string', 'B'],
  ['positive-boundary', undefined],
  ['negative-outside', undefined],
  ['positive-infinity', undefined],
  ['negative-infinity', undefined],
  ['empty-still-converts-index', [undefined, ['index']]],
  ['hole-without-prototype-value', [undefined, false]],
  ['own-undefined', [undefined, true]],
  ['hole-with-local-inheritance', ['inherited', false]],
  ['inherited-getter-receiver', ['receiver', 1]],
  ['fractional-string-length', 'B'],
  ['negative-length', undefined],
  ['missing-length', undefined],
  ['nan-length', undefined],
  ['infinite-length-clamped', 'cap'],
  ['length-over-32-bits', 'wide'],
  ['proxy-in-range', ['C', ['get:length', 'get:2']]],
  ['proxy-out-of-range', [undefined, ['get:length']]],
  ['coercion-order', ['B', ['length', 'index', 'get:1']]],
  ['length-snapshot', ['C', ['length', 'index', 'get:2']]],
  ['throwing-length-stops-index', ['RangeError', ['length']]],
  ['bigint-index', 'TypeError'],
  ['symbol-index', 'TypeError'],
  ['null-receiver', 'TypeError'],
  ['undefined-receiver', 'TypeError'],
  ['bigint-length', 'TypeError']
];

文件 2,教学模型:at-model.cjs

// Teaching model: a normal function, not a global polyfill.
function integer(value) {
  const n = +value;
  if (Number.isNaN(n) || n === 0) return 0;
  return Number.isFinite(n) ? Math.trunc(n) || 0 : n;
}
function lengthOf(object) {
  return Math.min(Math.max(integer(object.length), 0), 2 ** 53 - 1);
}
function readAt(receiver, index) {
  if (receiver === null || receiver === undefined) {
    throw new TypeError('Receiver cannot be null or undefined');
  }
  const object = Object(receiver);
  const length = lengthOf(object);
  const n = integer(index);
  const k = n < 0 ? length + n : n;
  if (k < 0 || k >= length) return undefined;
  return object[k];
}
module.exports = { readAt, integer, lengthOf };

模型用一元加号完成数值转换,不能随意替换为 Number(value),因为 Number(1n) 与原生 at 接受 BigInt 索引时的行为不同。Math.trunc(n) || 0 仅在已排除 NaN、零和无穷大的分支中使用,将小于 1 的有限负数截断后统一为正零。

文件 3,36 个独立场景:cases.cjs

const abc = () => ['A', 'B', 'C'];
function errorName(action) {
  try { action(); return 'NO_ERROR'; }
  catch (error) { return error.name; }
}
function traceRead(read, index) {
  const log = [];
  const proxy = new Proxy({ 0: 'A', 1: 'B', 2: 'C', length: 3 }, {
    get(target, key, receiver) {
      log.push('get:' + String(key));
      return Reflect.get(target, key, receiver);
    },
    has(target, key) {
      log.push('has:' + String(key));
      return Reflect.has(target, key);
    }
  });
  return [read(proxy, index), log];
}
module.exports = [
  ['negative-last', read => read(abc(), -1)],
  ['positive-index', read => read(abc(), 1)],
  ['negative-first', read => read(abc(), -3)],
  ['literal-minus-one', read => {
    const a = abc();
    a['-1'] = 'side';
    return [read(a, -1), a[-1], a.length];
  }],
  ['omitted-index', read => read(abc())],
  ['negative-zero', read => read(abc(), -0)],
  ['nan-index', read => read(abc(), NaN)],
  ['positive-fraction', read => read(abc(), 1.9)],
  ['negative-fraction', read => read(abc(), -1.9)],
  ['negative-subunit', read => read(abc(), -0.9)],
  ['numeric-string', read => read(abc(), '-2')],
  ['positive-boundary', read => read({ 3: 'outside', length: 3 }, 3)],
  ['negative-outside', read => read({ '-1': 'outside', length: 3 }, -4)],
  ['positive-infinity', read => read(abc(), Infinity)],
  ['negative-infinity', read => read(abc(), -Infinity)],
  ['empty-still-converts-index', read => {
    const log = [];
    const index = { valueOf() { log.push('index'); return 0; } };
    return [read([], index), log];
  }],
  ['hole-without-prototype-value', read => {
    const a = new Array(1);
    Object.setPrototypeOf(a, null);
    return [read(a, 0), Object.hasOwn(a, '0')];
  }],
  ['own-undefined', read => {
    const a = [undefined];
    return [read(a, 0), Object.hasOwn(a, '0')];
  }],
  ['hole-with-local-inheritance', read => {
    const a = new Array(1);
    Object.setPrototypeOf(a, { 0: 'inherited' });
    return [read(a, 0), Object.hasOwn(a, '0')];
  }],
  ['inherited-getter-receiver', read => {
    let count = 0;
    const proto = { get 0() { count++; return this.label; } };
    const object = Object.assign(Object.create(proto), {
      label: 'receiver', length: 1
    });
    return [read(object, 0), count];
  }],
  ['fractional-string-length', read => read({
    0: 'A', 1: 'B', 2: 'C', length: '2.9'
  }, -1)],
  ['negative-length', read => read({ 0: 'hidden', length: -2 }, 0)],
  ['missing-length', read => read({ 0: 'hidden' }, 0)],
  ['nan-length', read => read({ 0: 'hidden', length: NaN }, 0)],
  ['infinite-length-clamped', read => read({
    [2 ** 53 - 2]: 'cap', length: Infinity
  }, -1)],
  ['length-over-32-bits', read => read({
    4294967296: 'wide', length: 4294967297
  }, -1)],
  ['proxy-in-range', read => traceRead(read, -1)],
  ['proxy-out-of-range', read => traceRead(read, 3)],
  ['coercion-order', read => {
    const log = [];
    const object = {
      get length() { log.push('length'); return 2; },
      get 1() { log.push('get:1'); return 'B'; }
    };
    const index = { valueOf() { log.push('index'); return -1; } };
    return [read(object, index), log];
  }],
  ['length-snapshot', read => {
    const log = [];
    let currentLength = 3;
    const object = {
      get length() { log.push('length'); return currentLength; },
      get 2() { log.push('get:2'); return 'C'; }
    };
    const index = { valueOf() {
      log.push('index'); currentLength = 1; return -1;
    } };
    return [read(object, index), log];
  }],
  ['throwing-length-stops-index', read => {
    const log = [];
    const object = { get length() {
      log.push('length'); throw new RangeError('length');
    } };
    const index = { valueOf() { log.push('index'); return 0; } };
    return [errorName(() => read(object, index)), log];
  }],
  ['bigint-index', read => errorName(() => read(abc(), 1n))],
  ['symbol-index', read => errorName(() => read(abc(), Symbol('i')))],
  ['null-receiver', read => errorName(() => read(null, 0))],
  ['undefined-receiver', read => errorName(() => read(undefined, 0))],
  ['bigint-length', read => errorName(() => read({ length: 1n }, 0))]
];

两个 Proxy 场景都只有一次有界调用。在本实验中,范围内读取的日志是 get:length、get:2;越界调用只有 get:length,没有 has 检查。这些日志来自“借用原型方法”的调用路径。若写成 proxy.at(-1),方法名 at 自身的查找也可能出现在日志中,不能直接拿两种日志逐项比较。

文件 4,10 个故意错误的变体:mutants.cjs

const { integer, lengthOf } = require('./at-model.cjs');
// Each mode demonstrates a deliberately wrong implementation.
function mutant(mode) {
  return (receiver, index) => {
    if (receiver === null || receiver === undefined) throw new TypeError();
    const object = Object(receiver);
    let n;
    if (mode === 'index-first') n = integer(index);
    let length = mode === 'length-uint32'
      ? object.length >>> 0 : lengthOf(object);
    if (mode === 'empty-shortcut' && length === 0) return undefined;
    if (mode !== 'index-first') {
      n = mode === 'floor-index' ? Math.floor(+index) : integer(index);
    }
    if (mode === 'reread-length') length = lengthOf(object);
    if (mode === 'nan-is-outside' && Number.isNaN(+index)) return undefined;
    if (mode === 'literal-negative' && n < 0) return object[n];
    let k = n < 0 ? length + n : n;
    if (mode === 'wrap-index' && length) k = ((n % length) + length) % length;
    if (mode !== 'skip-bounds' && (k < 0 || k >= length)) return undefined;
    if (mode === 'own-only' && !Object.hasOwn(object, k)) return undefined;
    return object[k];
  };
}
module.exports = [
  ['literal-negative', 'literal-minus-one'],
  ['floor-index', 'negative-fraction'],
  ['nan-is-outside', 'nan-index'],
  ['skip-bounds', 'positive-boundary'],
  ['own-only', 'hole-with-local-inheritance'],
  ['length-uint32', 'length-over-32-bits'],
  ['index-first', 'coercion-order'],
  ['reread-length', 'length-snapshot'],
  ['wrap-index', 'proxy-out-of-range'],
  ['empty-shortcut', 'empty-still-converts-index']
].map(([name, witness]) => ({ name, witness, read: mutant(name) }));

每个变体都要完成整组用例,并在指定 witness 上与预期不符,才算被测试拒绝。语法错误或意外崩溃不算成功抓错。它们分别模拟:把负数当属性名、向下取整、把 NaN 判为越界、省略边界检查、只查自有属性、长度截为 32 位、先转换索引、重复读取长度、循环索引和空数组提前退出。

文件 5,显式失败的测试入口:test.cjs

const { isDeepStrictEqual, inspect } = require('node:util');
const { readFileSync, writeFileSync } = require('node:fs');
const path = require('node:path');
const expected = require('./expected.cjs');
const cases = require('./cases.cjs');
const { readAt } = require('./at-model.cjs');
const mutants = require('./mutants.cjs');
if (cases.length !== 36 || expected.length !== cases.length) {
  throw new Error('Case count changed');
}
for (let i = 0; i < cases.length; i++) {
  if (cases[i][0] !== expected[i][0]) throw new Error('Oracle ID mismatch');
}
function check(read) {
  const failures = [];
  for (let i = 0; i < cases.length; i++) {
    const [id, run] = cases[i];
    const actual = run(read);
    if (!isDeepStrictEqual(actual, expected[i][1])) {
      failures.push({ id, actual: inspect(actual), expected: inspect(expected[i][1]) });
    }
  }
  return failures;
}
const lines = [];
for (const [name, read] of [
  ['native', (receiver, index) => Array.prototype.at.call(receiver, index)],
  ['model', readAt]
]) {
  const failures = check(read);
  if (failures.length) throw new Error(name + ': ' + JSON.stringify(failures));
  lines.push('PASS ' + name + ' 36/36');
}
const mutationReport = [];
if (mutants.length !== 10) throw new Error('Mutation count changed');
for (const { name, witness, read } of mutants) {
  // Unexpected exceptions abort the run: they do not count as a killed mutant.
  const failures = check(read);
  if (!failures.some(item => item.id === witness)) {
    throw new Error('Mutation survived its witness: ' + name);
  }
  mutationReport.push({ name, witness, failures });
}
lines.push('PASS mutations 10/10 rejected');
const output = lines.join('\n') + '\n';
const golden = readFileSync(path.join(__dirname, 'expected-output.txt'), 'utf8');
const wanted = golden.endsWith('\n') ? golden : golden + '\n';
if (output !== wanted) throw new Error('Output differs from frozen file');
if (process.env.REPORT_FILE) {
  writeFileSync(process.env.REPORT_FILE, JSON.stringify({
    node: process.version, execArgv: process.execArgv,
    passed: { native: 36, model: 36, mutations: 10 }, mutationReport
  }, null, 2) + '\n');
}
process.stdout.write(output);

文件 6,固定标准输出:expected-output.txt

PASS native 36/36
PASS model 36/36
PASS mutations 10/10 rejected

六、运行结果与适用边界

在上述文件所在目录运行以下命令。quick-demo.cjs 会依次输出 publish、note、3、draft、draft、publish;两次 test.cjs 的输出都应与 expected-output.txt 完全一致。

node --version
node quick-demo.cjs
node test.cjs
node --use-strict test.cjs

本次 Node v24.19.0 实测:原生方法 36/36、教学模型 36/36;10/10 个语义错误变体被指定用例拒绝。普通与 --use-strict 两次启动均通过,标准输出逐字节一致;从本文 HTML 还原出的文件也在独立目录重新执行过。这是本组输入的验证结果,不是性能测试或全实现一致性认证。

实际写业务代码时,已知是普通稠密数组且只想取最后一项,用 items.at(-1) 即可。面对外部传入的类数组、Proxy 或带 getter 的对象,先考虑 length 和索引转换是否可信;面对返回的 undefined,别忘了它本身不包含“空洞、越界还是存储值”的原因。

参考与核验记录

文档核验与本地测试日期:2026 年 10 月 22 日,北京时间。规范链接为持续更新的工作草案,不把页面上的未来版次标识当作本机运行时已经实现全部新特性的证明。本文案例与代码为独立设计。

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