JavaScript at 方法
最后修改于 2025 年 4 月 4 日
在本文中,我们将展示如何使用 JavaScript 中的 at 方法访问数组元素。
访问数组元素
at 方法接受一个整数值,并返回该索引处的项目。 它允许正整数和负整数,其中负整数从数组的最后一个项目开始倒数。
此方法为括号表示法提供了一个更易读的替代方案,尤其是在从数组末尾访问元素时。 它是在 ES2022 中引入的,用于简化常见的数组访问模式。
at 方法的工作方式类似于括号表示法,但更好地处理负索引。 如果索引超出范围,它将返回 undefined,就像括号表示法一样。
基本 at() 示例
以下示例演示了 at 方法的基本用法。
main.js
const fruits = ['apple', 'banana', 'cherry']; console.log(fruits.at(0)); // First element console.log(fruits.at(-1)); // Last element console.log(fruits.at(5)); // Out of bounds
我们创建一个数组,并使用正索引和负索引访问元素。 at 方法提供了一种干净的方式来访问数组两端的元素。
$ node main.js apple cherry undefined
将 at() 与括号表示法进行比较
at 方法提供与括号表示法类似的功能,但对于负索引具有更好的可读性。
main.js
const colors = ['red', 'green', 'blue']; // Using bracket notation const last1 = colors[colors.length - 1]; // Using at() const last2 = colors.at(-1); console.log(last1); console.log(last2);
我们比较使用括号表示法和 at 方法访问最后一个元素。 当处理数组末尾的元素时,at 版本更简洁易读。
$ node main.js blue blue
将 at() 用于字符串
at 方法也适用于字符串,通过位置提供字符访问。
main.js
const message = "Hello World"; console.log(message.at(0)); // First character console.log(message.at(-1)); // Last character console.log(message.at(-3)); // Third from last
我们使用 at 访问字符串中的字符。 对于字符串,该方法的行为与数组相同,支持正索引和负索引。
$ node main.js H d r
at() 与类型化数组
at 方法也可用于类型化数组,例如 Int8Array。
main.js
const intArray = new Int8Array([10, 20, 30, 40]); console.log(intArray.at(1)); // Second element console.log(intArray.at(-2)); // Third element
我们演示了将 at 用于类型化数组。 该方法在 JavaScript 中不同的类似数组的对象中表现一致,包括类型化数组。
$ node main.js 20 30
在数组方法中使用 at()
at 方法可以在其他数组方法中使用,以获得更具表现力的代码。
main.js
const numbers = [1, 2, 3, 4, 5];
const lastTwo = numbers.slice(-2).map((_, i, arr) =>
arr.at(i - 1) + arr.at(i)
);
console.log(lastTwo);
我们在 map 回调中使用 at 访问相邻元素。 这演示了 at 如何简化需要相对索引的数组操作。
$ node main.js [ 7, 9 ]
来源
在本文中,我们演示了如何使用 at() 方法访问 JavaScript 数组和字符串中的元素。
作者
列出 所有 JS 数组函数。