javascript 的 at() 方法支持正负索引安全访问数组等类数组对象元素,越界返回 undefined 而不报错,兼容字符串和 typedarray,es2022 新增,旧环境需 polyfill。

JavaScript 的 at() 方法专为安全访问数组(或字符串、类数组对象)元素而设计,它支持正向索引(从 0 开始)和负向索引(从 -1 开始表示末尾),且不会因越界返回 undefined 而报错——这本身就是“安全”的体现。
支持负向索引,直接定位末尾元素
at() 允许用负数下标从末尾往前取值,无需手动计算 length + index。例如:
-
[1, 2, 3].at(-1)→3(最后一个) -
[1, 2, 3].at(-2)→2(倒数第二个) -
[1, 2, 3].at(-10)→undefined(越界不报错,返回undefined)
比方括号语法更安全:越界不报错,也不改变行为逻辑
传统 arr[-1] 始终返回 undefined(因为负数不是有效属性名),而 at(-1) 是语义明确的“取倒数第 1 个”。更重要的是,at() 对所有越界情况(正向超长、负向过深)统一返回 undefined,不会触发异常,适合用于容错读取:
-
[10].at(5)→undefined -
[10].at(-5)→undefined -
[].at(0) →undefined
可用于字符串和类数组对象
at() 是通用方法,只要对象有 length 属性和数字索引(如字符串、arguments、TypedArray),就能用:
-
"hello".at(-1)→"o" -
new Uint8Array([7, 8]).at(-1)→8 -
Array.from({ length: 2, 0: "a", 1: "b" }).at(-1)→"b"
注意兼容性与 polyfill 方案
at() 是 ES2022 新增特性,现代浏览器和 Node.js ≥16.6 已原生支持。若需兼容旧环境,可手动添加轻量 polyfill:
(仅当目标环境不支持时才需引入)
if (!Array.prototype.at) {
Array.prototype.at = function(n) {
const arr = Object(this);
const len = arr.length >>> 0;
const idx = Math.floor(n) || 0;
return idx >= 0 ? arr[idx] : arr[len + idx];
};
}Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











