领先的免费Web技术教程,涵盖HTML到ASP.NET

网站首页 > 知识剖析 正文

ts 获取数组的最后一项数据 ts 数组对象

nixiaole 2024-11-10 12:30:47 知识剖析 21 ℃

在TypeScript中,获取数组的最后一项有几种常见方式:

直接通过数组的 length 属性和下标访问

const array: any[] = [1, 2, 3, 4, 5];
const lastElement = array[array.length - 1];
console.log(lastElement); // 输出 5

使用 ES6 的解构赋值

const array: number[] = [1, 2, 3, 4, 5];
const [, ...rest, last] = array;
console.log(last); // 输出 5

使用 pop() 方法(该方法会改变原数组)

const array: number[] = [1, 2, 3, 4, 5];
const lastElement = array.pop();
console.log(lastElement); // 输出 5,此时array变为[1, 2, 3, 4]

使用 slice() 方法(不会改变原数组):

const array: number[] = [1, 2, 3, 4, 5];
const lastElement = array.slice(-1)[0];
console.log(lastElement); // 输出 5

其中,第一种方法最为常见且直观,适用于大多数场景。而第三种方法虽然最快,但改变了原数组,如果不是有意为之,通常不推荐这样做。第四种方法使用了负索引,它可以从数组的末尾开始截取元素,同样不会影响原数组。

Tags:

最近发表
标签列表