发布于 2026-01-06 1 阅读
0

停止使用 Array[index],改用 Array.at()。

停止使用 Array[index],改用 Array.at()。

Array.at()这是一个全新的 JavaScript 数组方法,它解决了标准数组元素访问方法中许多常见问题Array[index]。有了它,我们终于可以在 JavaScript 中原生实现负索引了。

负指数

负索引是指使用负数作为索引,从数组末尾而不是开头访问元素。例如,如果您想获取名为 `a` 的数组中的最后一个元素arr,您应该使用 `a` arr[-1]。遗憾的是,在 JavaScript 中,这种做法并不像我们预期的那样,因为这种[]语法不适用于数组和字符串,而是适用于所有对象。

使用对象时,语法[]规则是获取具有指定键的对象的属性。由于数组和字符串也是对象,因此这条规则同样适用于它们。在底层,数组和字符串会将每个元素分配给与其当前索引匹配的键。

// When it comes to indexing, 'arr' behaves exactly like 'obj'
const arr = ['cat', 'dog', 'fish', 'bird'];

const obj = {
   0: 'cat',
   1: 'dog',
   2: 'fish',
   3: 'bird'
};
Enter fullscreen mode Exit fullscreen mode

所以arr[-1]这已经是有效的 Javascript 代码了,但是它并没有返回最后一个元素,而是尝试返回数组中“-1”键的值,这通常是undefined

现有变通方案

目前有几种方法可以实现这种行为。第一种方法是从数组长度中减去负索引。

const pets = ['cat', 'dog', 'fish', 'bird'];
const lastPet = pets[pets.length - 1];

console.log(lastPet); // Prints out 'bird'
Enter fullscreen mode Exit fullscreen mode

这种方法可行,也是大多数开发者绕过这个限制的方法,但存在一些问题:

  • 数组名称被调用了两次,而且通常都很长。
  • 这不能用于尚未赋值给变量的值。
  • 除非先将函数返回值的最后一项存储在临时变量中,否则无法使用此方法获取该返回值的最后一项。
['cat', 'dog', 'fish', 'bird'][ **what do you put here** - 1];

const a = () => ['cat', 'dog', 'fish', 'bird']; 
a()[ **What do you out here** - 1];
Enter fullscreen mode Exit fullscreen mode

另一种方法是使用Array.slice()内置负索引的索引器。

const pets = ['cat', 'dog', 'fish', 'bird'];
const lastPet = pets.slice(-1)[0];

console.log(lastPet); // Prints out 'bird'
Enter fullscreen mode Exit fullscreen mode

这实际上解决了先前方法中的许多问题,但也引入了一些新问题:

  • 语法不太容易理解,特别是末尾的 `ascise`,[0]因为它返回的是一个数组。
  • 创建一个从所需索引到数组末尾的临时数组,并立即将其丢弃。

Array.at()

这就是Array.at()实现的原因。它对Array[index]正数的处理方式完全相同,但对负数则正确地实现了负索引。

const pets = ['cat', 'dog', 'fish', 'bird'];
const lastPet = pets.at(-1);

console.log(lastPet); // Prints out 'bird'
Enter fullscreen mode Exit fullscreen mode

这种方法语法更简洁,而且不会造成任何性能损失。目前大多数现代浏览器都支持此功能,如有需要,还可以使用相应的 Polyfill。

如果您想了解更多信息,请查看MDN上的相关文档。您也可以阅读最初的提案

文章来源:https://dev.to/timotius/stop-using-arrayindex-use-arrayat-instead-44ka