JavaScript at 方法详解:负索引、缺失值与字符串码元边界
读取数组末项看似只需要记住 at(-1),真正容易出错的却是方法之外的假设:负数方括号、缺失值判断、索引转换和字符串长度。本文用五组正确用法与错误假设,说明 Array.prototype.at 适合做什么,以及 String、TypedArray 同名方法有哪些边界。
全部十段程序均在 Node.js v24.19.0 独立进程中实测,使用内置 node:assert/strict,不需安装依赖。每段可单独保存为 .cjs 文件,再用 node 文件名.cjs 运行。下面的输出直接取自各次执行;所有脚本退出码为零、标准错误为空。“错误假设”指待推翻的理解,不是让读者复制一个必然失败的断言。
语义依据为 ECMA-262 第17版(2026年6月);测试范围仅代表上述运行环境,不据此推断浏览器兼容性或性能。

正确示例一 从尾部读取 不改变数组
取最后一条日志时,values.at(-1) 比手写长度减一更直观。负数表示相对末尾的位置,负一取最后一项,负三在这个三元素数组里取第一项。零仍然表示开头;正索引等于长度、负索引小于负长度以及空数组读取,都返回 undefined。
这不是循环下标,越界不会绕回起点,也不是弹出操作。下面同时比较调用前后的内容:读取末项不会缩短数组。需要覆盖、删除或移出元素,应另选相应的写入操作,不能把读取方法当成更新接口。
独立程序 01_correct_relative_read.cjs
const assert = require('node:assert/strict');
const values = ['red', 'green', 'blue'];
const before = [...values];
assert.equal(values.at(0), 'red');
assert.equal(values.at(-1), 'blue');
assert.equal(values.at(-3), 'red');
assert.equal(values.at(3), undefined);
assert.equal(values.at(-4), undefined);
assert.equal([].at(-1), undefined);
assert.deepEqual(values, before);
console.log('first:', values.at(0), 'last:', values.at(-1));
console.log('bounds:', values.at(3), values.at(-4), [].at(-1));
console.log('unchanged:', JSON.stringify(values));
实际标准输出
first: red last: blue bounds: undefined undefined undefined unchanged: ["red","green","blue"]
错误假设一 方括号负数也是倒数索引
在普通数组上,values[-1] 访问的是名为“-1”的属性,不会先计算长度。给它赋值,只会在本例中增加一个普通自有属性,原来的最后一个元素仍是 blue,长度仍是三。
这类错误常见于从其他语言迁移的代码:日志里确实能读到刚写入的值,于是误以为更新了末项。反例用断言确认两条访问路径的结果不同;这里只讨论普通数组,不能把这个属性行为原样套到 TypedArray。
独立程序 02_wrong_negative_property.cjs
const assert = require('node:assert/strict');
const values = ['red', 'green', 'blue'];
assert.equal(values[-1], undefined);
values[-1] = 'side-property';
assert.equal(values[-1], 'side-property');
assert.equal(values.at(-1), 'blue');
assert.equal(values.length, 3);
assert.notEqual(values[-1], values.at(-1));
console.log('bracket:', values[-1]);
console.log('at:', values.at(-1), 'length:', values.length);
console.log('own -1:', Object.hasOwn(values, '-1'));
实际标准输出
bracket: side-property at: blue length: 3 own -1: true
对应规范:Array.prototype.at 算法。
正确示例二 先理解索引转换再依赖简写
索引不是仅接受整数。规范先进行数值转换,再将有限小数向零截断:一点九变成一,负一点九变成负一。负零和 NaN 都按零处理;正负 Infinity 在下面的有限数组上均越界。字符串“-2”可以转成数字,显式传 undefined 也会落到开头。
这些是运行结果,不是输入校验策略。业务若只允许整数,应在调用前检查,不要让错误输入静默读取首项。BigInt 与 Symbol 在这里抛出 TypeError,示例明确捕获并验证,未将异常伪装成 undefined。
独立程序 03_correct_index_coercion.cjs
const assert = require('node:assert/strict');
const values = ['A', 'B', 'C'];
const cases = [
['1.9', 1.9, 'B'], ['-1.9', -1.9, 'C'],
['-0', -0, 'A'], ['NaN', NaN, 'A'],
['Infinity', Infinity, undefined],
['-Infinity', -Infinity, undefined],
['string -2', '-2', 'B'], ['undefined', undefined, 'A'],
];
for (const [label, index, expected] of cases) {
const actual = values.at(index);
assert.equal(actual, expected);
console.log(label + ' =>', actual);
}
assert.throws(() => values.at(1n), TypeError);
assert.throws(() => values.at(Symbol('index')), TypeError);
console.log('BigInt and Symbol: TypeError (caught)');
实际标准输出
1.9 => B -1.9 => C -0 => A NaN => A Infinity => undefined -Infinity => undefined string -2 => B undefined => A BigInt and Symbol: TypeError (caught)
错误假设二 负小数先向下取整
将转换写成 Math.floor 会改变负数结果。负一点九向下取整为负二,但 at 使用向零截断,实际读倒数第一项。更容易漏掉的是负零点九:它截断到零,于是读取第一项,而不是最后一项。
下面将错误算法的预测值和真实结果并列输出,再断言两者不同。不要根据参数带有负号,就提前选择“从末尾读取”的分支;决定分支的是转换后的整数,而不是原始文本或原始数值的符号。
独立程序 04_wrong_fraction_floor.cjs
const assert = require('node:assert/strict');
const values = ['A', 'B', 'C'];
for (const index of [-1.9, -0.9]) {
const floorGuess = values.at(Math.floor(index));
const actual = values.at(index);
assert.notEqual(actual, floorGuess);
console.log(index, 'floor guess:', floorGuess, 'actual:', actual);
}
assert.equal(values.at(-1.9), 'C');
assert.equal(values.at(-0.9), 'A');
实际标准输出
-1.9 floor guess: B actual: C -0.9 floor guess: C actual: A
转换依据:ToIntegerOrInfinity。
正确示例三 借用数组方法读取类数组
Array.prototype.at 可以通过 call 借给带 length 的普通对象。它按长度和索引属性读取,不要求对象真的继承 Array.prototype,也不依赖迭代器。本例对象没有自己的 at 方法,却能读取最后一项。
索引访问采用普通属性读取,因此原型上的值也可能被读到。示例的一号属性来自原型,读取得到 inherited,但 Object.hasOwn 返回 false。需要只接受自有数据时,要单独制定检查规则,不能以 at 成功返回值作为证据。
独立程序 05_correct_generic_arraylike.cjs
const assert = require('node:assert/strict');
const list = Object.assign(Object.create({ 1: 'inherited' }), {
0: 'first', 2: 'last', length: 3,
});
const read = (index) => Array.prototype.at.call(list, index);
assert.equal(read(-1), 'last');
assert.equal(read(1), 'inherited');
assert.equal(read(3), undefined);
assert.equal(Object.hasOwn(list, '1'), false);
console.log('last:', read(-1));
console.log('inherited:', read(1), 'own:', Object.hasOwn(list, '1'));
console.log('outside:', read(3));
实际标准输出
last: last inherited: inherited own: false outside: undefined
错误假设三 返回 undefined 就说明位置不存在
空洞、存在且值恰好为 undefined 的元素,以及越界位置,都可能给出相同读取结果。下面零号位置是空洞,一号位置是实际存在的元素,二号位置越界,三个返回值却完全一致。
先明确你问的是哪件事:范围检查回答索引是否处于长度内;Object.hasOwn 回答对象是否直接持有该属性;in 还会考虑原型链。若使用负索引检查存在性,应先按同一转换规则算出实际非负位置,不能直接检查名为“-1”的属性。
独立程序 06_wrong_undefined_means_absent.cjs
const assert = require('node:assert/strict');
const values = [, undefined];
const reads = [values.at(0), values.at(1), values.at(2)];
const own = [0, 1, 2].map((index) => Object.hasOwn(values, index));
assert.deepEqual(reads, [undefined, undefined, undefined]);
assert.deepEqual(own, [false, true, false]);
assert.equal(1 in values, true);
console.log('reads:', ...reads);
console.log('own:', ...own);
console.log('inside length:', 0 < values.length, 1 < values.length, 2 < values.length);
实际标准输出
reads: undefined undefined undefined own: false true false inside length: true true false
相关定义:LengthOfArrayLike、Object.hasOwn。
正确示例四 字符串读取的是 UTF-16 码元
String.prototype.at 的计数单位是 UTF-16 码元,不是人眼看到的字符。字符串 A😀 的长度是三;表情由两个码元组成,分别是十六进制 D83D 和 DE00,末尾读取只得到后一个。
示例用 charCodeAt 显示码元,避免终端把孤立代理项画成替代符而掩盖真实结果。字符串迭代器按码点遍历,所以展开后能完整取到这个表情;但这只解决码点层面的拆分,仍不等于按可见字素分段。
独立程序 07_correct_string_codeunits.cjs
const assert = require('node:assert/strict');
const text = 'A😀';
assert.equal(text.length, 3);
assert.equal(text.at(1).charCodeAt(0), 0xD83D);
assert.equal(text.at(-1).charCodeAt(0), 0xDE00);
assert.equal(text.at(3), undefined);
assert.equal([...text].length, 2);
assert.equal([...text].at(-1), '😀');
console.log('UTF-16 length:', text.length);
console.log('units:', text.at(1).charCodeAt(0).toString(16), text.at(-1).charCodeAt(0).toString(16));
console.log('code-point last:', [...text].at(-1));
console.log('outside:', text.at(3));
实际标准输出
UTF-16 length: 3 units: d83d de00 code-point last: 😀 outside: undefined
错误假设四 at 适合直接截取最后一个可见字符
对 A😀 调用 at(-1) 不会返回完整表情。另一个例子把字母 e 和组合重音符拼在一起,它们可以共同形成一个可见字符,但 at 只取出最后的重音码元。
即使先展开字符串,本例仍会得到两个码点,末项依然只是重音符。因此,用户名截断、光标移动和展示字数不能仅靠 at 或展开运算符推断。应先确定业务要求按码元、码点还是字素处理,再选择分段方案;这里不把一个表情样例推广成所有文字的解决办法。
独立程序 08_wrong_last_visible_character.cjs
const assert = require('node:assert/strict');
const emojiText = 'A😀';
const combiningText = 'e\u0301';
assert.notEqual(emojiText.at(-1), '😀');
assert.equal(emojiText.at(-1).charCodeAt(0), 0xDE00);
assert.notEqual(combiningText.at(-1), combiningText);
assert.equal(combiningText.at(-1), '\u0301');
assert.equal([...combiningText].at(-1), '\u0301');
console.log('emoji tail:', JSON.stringify(emojiText.at(-1)));
console.log('combining tail unit:', combiningText.at(-1).charCodeAt(0).toString(16));
console.log('code points:', [...combiningText].length);
实际标准输出
emoji tail: "\ude00" combining tail unit: 301 code points: 2
相关规范:String.prototype.at、字符串迭代器。
正确示例五 TypedArray 支持同样的相对读取
对于本例这个普通、有效的 Uint8Array,原生 at(-1) 返回末尾数值,越界返回 undefined。借用 Array.prototype.at 也能完成这里的索引读取,但这不代表两个方法在所有接收者上都等价。
断言还核对了读取前后的元素,说明 at 没有替换字节或删除末项。本文没有测试已分离或可调整缓冲区的边界,不把普通有效视图的结果推广到这些状态;数组与类型化数组的属性规则也应分别理解。
独立程序 09_correct_typedarray_read.cjs
const assert = require('node:assert/strict');
const bytes = new Uint8Array([10, 20, 30]);
const before = [...bytes];
assert.equal(bytes.at(-1), 30);
assert.equal(bytes.at(3), undefined);
assert.equal(Array.prototype.at.call(bytes, -1), 30);
assert.deepEqual([...bytes], before);
console.log('typed:', bytes.at(-1));
console.log('array generic:', Array.prototype.at.call(bytes, -1));
console.log('outside:', bytes.at(3));
console.log('unchanged:', JSON.stringify([...bytes]));
实际标准输出
typed: 30 array generic: 30 outside: undefined unchanged: [10,20,30]
错误假设五 TypedArray 方法也能任意借用
TypedArray 的 at 会先校验接收者是不是类型化数组。只有数字属性和 length 的伪对象不能通过这一检查,调用会抛出 TypeError;Array.prototype.at 在同一个对象上却能读到二十。
下面捕获并断言这个预期异常,脚本仍正常退出。选用哪个方法时,要区分“把类型化数组交给通用数组方法”与“把普通对象交给类型化数组方法”。方向不同,前提不同,不能只看方法名相同就互相替换。
独立程序 10_wrong_typedarray_borrow.cjs
const assert = require('node:assert/strict');
const fake = { 0: 10, 1: 20, length: 2 };
let errorName;
assert.throws(() => {
try {
Uint8Array.prototype.at.call(fake, -1);
} catch (error) {
errorName = error.name;
throw error;
}
}, TypeError);
const generic = Array.prototype.at.call(fake, -1);
assert.equal(generic, 20);
console.log('typed method:', errorName, '(caught)');
console.log('array generic:', generic);
实际标准输出
typed method: TypeError (caught) array generic: 20
接收者校验依据:TypedArray.prototype.at。
把读取位置和业务含义分开
at 的核心用途是按相对位置读值。日常代码中,应把三个问题分开:位置如何转换、这个位置是否满足业务约束、返回值是否有效。尤其不要用 undefined 同时表达“越界”“缺字段”和“明确存入空值”,再指望读取方法替你区分。
本身没有写入或删除步骤,也不意味着面对任意对象都没有副作用:读取 length 或索引属性时,getter 或 Proxy 仍可能执行用户代码。若读出的是对象,拿到的也是该对象的引用,而不是深复制。这些语义边界比把所有下标统一改成 at 更值得保留在代码审查清单里。
复现实测所用官方资料:Node.js v24.19.0 发布目录与该版本的断言模块文档。

