你应该会喜欢的的新语法 .at

503 阅读1分钟

看推特偶然间看到的

JavaScript的新.at()方法允许你根据索引选择项。  

这对于获取数组或字符串的最后一项非常方便,因为与数组不同,它支持负索引!

原文

平常我们获取数组的最后一个元素的时候通常会使用 .length - 1, 有了 at 方法就不需要这么麻烦了

const arr = [1,2,3,4,5]
arr[arr.length - 1] // 5
arr.at(-1)  // 5
'AB'.at(-1) // B 字符串也有此方法

不过如果下标大于数组的长度会返回undefined

负数开始的顺序

-1 等于 正序的 0

所以 -4 等于 3

[1,2,3].at(-4)
// undefined