在JavaScript中,有几种不同的方法可以用来获取数组的最后一个元素。以下是其中的一些方法:
- 使用数组的length属性和负索引:
let arr = [1, 2, 3, 4, 5];
let lastElement = arr[arr.length - 1];
console.log(lastElement); // 输出:5
- 使用数组的pop方法:
let arr = [1, 2, 3, 4, 5];
let lastElement = arr.pop();
console.log(lastElement); // 输出:5
console.log(arr); // 输出:[1, 2, 3, 4]
- 使用数组的slice方法:
let arr = [1, 2, 3, 4, 5];
let [lastElement] = arr.slice(-1);
console.log(lastElement); // 输出:5
- 使用ES6的扩展运算符:
let arr = [1, 2, 3, 4, 5];
let [firstElement, ...otherElements, lastElement] = arr;
console.log(lastElement); // 输出:5