js如何获取数组的最后一个元素

1.索引,直接利用获取第length-1位;

2.pop()方法:
会改变原数组

let list =[10,5,7,8,4,3];
console.log(list.pop());// 1
console.log(list)//[ 10, 5, 7, 8, 4 ]

3.slice()方法
不会改变原数组

let list =[10,5,7,8,4,3];
console.log(list.slice(-1));//[ 3 ]
console.log(list);//[ 10, 5, 7, 8, 4, 3 ]

4…at(index):
可以获取到index索引处的元素(就是这么直接)
.at()是ES2022的新语法,目前兼容性还不是很好,慎用!
.at()支持正索引和负索引

猜你喜欢

转载自blog.csdn.net/qq_42931285/article/details/124996402