获取数组中的最后一项
技术背景
在 JavaScript 开发中,获取数组的最后一项是一个常见的需求。例如,在处理 URL 路径、解析数据列表等场景下,经常需要获取数组的最后一个元素。不同的实现方式在性能、代码简洁性和兼容性方面存在差异,因此了解多种获取数组最后一项的方法是很有必要的。
实现步骤
1. 使用 length
属性
1 2 3
| const arr = [1, 2, 3, 4]; const last = arr[arr.length - 1]; console.log(last);
|
2. 使用 Array.prototype.at()
方法(ES2022)
1 2 3
| const arr = [1, 2, 3, 4]; const last = arr.at(-1); console.log(last);
|
3. 使用 Array.prototype.slice()
方法
1 2 3
| const arr = [1, 2, 3, 4]; const last = arr.slice(-1)[0]; console.log(last);
|
4. 使用 Array.prototype.pop()
方法
1 2 3 4
| const arr = [1, 2, 3, 4]; const last = arr.pop(); console.log(last); console.log(arr);
|
5. 使用解构赋值和 slice()
方法
1 2 3
| const lotteryNumbers = [12, 16, 4, 33, 41, 22]; const [lastNumber] = lotteryNumbers.slice(-1); console.log(lastNumber);
|
6. 使用 findLast
方法(提案阶段)
1 2 3
| const arr = [1, 2, 3, 4]; const last = arr.findLast(x => true); console.log(last);
|
7. 使用自定义函数
1 2 3 4 5 6
| function last(arr) { return arr[arr.length - 1]; }
const arr = [1, 2, 3, 4]; console.log(last(arr));
|
8. 使用第三方库
Lodash
1 2 3 4
| const _ = require('lodash'); const arr = [1, 2, 3, 4]; const last = _.last(arr); console.log(last);
|
Ramda
1 2 3 4
| const R = require('ramda'); const arr = [1, 2, 3, 4]; const last = R.last(arr); console.log(last);
|
核心代码
以下是一些常用方法的代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| const getLastByLength = (arr) => arr[arr.length - 1];
const getLastByAt = (arr) => arr.at(-1);
const getLastBySlice = (arr) => arr.slice(-1)[0];
const getLastByPop = (arr) => { const newArr = [...arr]; return newArr.pop(); };
const arr = [1, 2, 3, 4]; console.log(getLastByLength(arr)); console.log(getLastByAt(arr)); console.log(getLastBySlice(arr)); console.log(getLastByPop(arr));
|
最佳实践
- 性能优先:如果追求性能,建议使用
arr[arr.length - 1]
或 arr.at(-1)
,它们的性能较高。 - 代码简洁性:如果注重代码的简洁性和可读性,可以使用第三方库提供的方法,如
_.last(arr)
或 R.last(arr)
。 - 避免修改原数组:如果不希望修改原数组,应避免使用
pop()
和 splice()
方法,可以使用 slice()
或 at()
方法。
常见问题
1. pop()
方法会修改原数组
使用 pop()
方法会移除原数组的最后一个元素,如果不希望修改原数组,可以先复制一份数组再使用 pop()
方法。
2. 兼容性问题
Array.prototype.at()
方法是 ES2022 新增的方法,在旧版本浏览器中可能不支持。在使用时需要考虑兼容性问题,可以使用 arr[arr.length - 1]
作为替代方案。
3. 数组为空的情况
当数组为空时,使用 arr[arr.length - 1]
、arr.at(-1)
和 arr.slice(-1)[0]
会返回 undefined
,使用 pop()
方法也会返回 undefined
,需要根据具体需求进行处理。