Getting the last element of an array is a frequently encountered scenario, and you must have your own commonly used methods. Maybe there's a moment when you're thinking as much as I am: "How does it count to be elegant?".
Suppose we have the following array:
let arr = ['cat','doggy','pig'];
Take a look at what methods are available to get the last element of an array, and see which one you use most often.
by length
arr[arr.length-1]
'pig'
arr.slice()
arr.slice(-1)[0]
'pig'
arr.pop()
arr.pop() // 会改变原素组
arr.slice(-1).pop() // 这样不会改变原数组
The above methods can be implemented, but they are not elegant. The following is the method I think is more elegant.
Array.prototype.at()
arr.at(-1)
'pig'
Simple and clear, in one step. What do you think? There is a better way, let me know in the comments.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。