📅  最后修改于: 2023-12-03 15:40:03.921000             🧑  作者: Mango
在 JavaScript 中,我们经常需要访问数组的最后一个元素。一种简单的方法是使用数组的 length
属性和索引,如下所示:
const arr = [1, 2, 3];
const lastElement = arr[arr.length - 1];
console.log(lastElement); // 输出 3
这将返回数组 arr
的最后一个元素。我们使用 arr.length - 1
计算了数组中最后一个元素的索引,然后在数组中访问它。
另一种方法是使用数组对象的 pop()
方法。pop()
方法会从数组中移除并返回最后一个元素:
const arr = [1, 2, 3];
const lastElement = arr.pop();
console.log(lastElement); // 输出 3
console.log(arr); // 输出 [1, 2]
以上代码将返回数组 arr
的最后一个元素,并将它从数组中移除。现在,arr
只包含前两个元素。
需要注意的是,使用 pop()
方法会修改原始数组。如果你需要保留原始数组,可以先将它复制到另一个数组中:
const arr = [1, 2, 3];
const newArr = [...arr];
const lastElement = newArr.pop();
console.log(lastElement); // 输出 3
console.log(arr); // 输出 [1, 2, 3]
console.log(newArr); // 输出 [1, 2]
以上代码将原始数组 arr
复制到一个新数组 newArr
中,然后从 newArr
中移除最后一个元素。原始数组 arr
不会被修改,仍然包含所有三个元素。
最后要注意的是,如果数组是空数组,以上方法都会返回 undefined
。因此,在访问数组的最后一个元素之前,应该先检查数组是否为空:
const arr = [];
if(arr.length > 0) {
const lastElement = arr[arr.length - 1];
console.log(lastElement);
} else {
console.log('数组为空');
}