访问TypeScript数组的最后一个元素

iyfamqjs  于 2023-05-08  发布在  TypeScript
关注(0)|答案(9)|浏览(305)

在TypeScript中,是否有一种符号来访问数组的最后一个元素?在Ruby中,我可以说:array[-1] .有类似的吗?

qlfbtfca

qlfbtfca1#

你可以通过它的索引来访问数组元素。数组中最后一个元素的索引将是数组的长度-1(因为索引是从零开始的)。
这个应该能用

var items: String[] = ["tom", "jeff", "sam"];

alert(items[items.length-1])

这是一个工作样本。

hiz5n14c

hiz5n14c2#

如果以后不需要数组,可以使用

array.pop()

但这会从数组中删除元素!

pop返回T | undefined,因此您需要在实现中注意这一点。
如果你确定总有一个值,你可以使用非空Assert运算符!):

var poped = array.pop()
     array.push(poped!);
w7t8yxp5

w7t8yxp53#

还有一种方法还没有提到:

items.slice(-1)[0]
uplii1fm

uplii1fm4#

截至2021年7月,浏览器开始支持数组的at()方法,该方法允许以下语法:

const arr: number[] = [1, 2, 3];

// shows 3
alert(arr.at(-1));

我不清楚TypeScript将在什么时候开始支持这一点(它还不适合我),但我猜它应该很快就会可用。

**编辑:**自typescript@4.5.4起可用

bf1o4zei

bf1o4zei5#

这里有一个选项总结在一起,为任何人发现这个问题晚像我一样。

var myArray = [1,2,3,4,5,6];

// Fastest method, requires the array is in a variable
myArray[myArray.length - 1];

// Also very fast but it will remove the element from the array also, this may or may 
// not matter in your case.
myArray.pop();

// Slowest but very readable and doesn't require a variable
myArray.slice(-1)[0]
ergxz8rk

ergxz8rk6#

如果你需要更频繁地调用这个函数,可以全局声明它:

interface Array<T> {
    last(): T | undefined;
}
if (!Array.prototype.last) {
    Array.prototype.last = function () {
        if (!this.length) {
            return undefined;
        }
        return this[this.length - 1];
    };
}

你就可以打电话

items.last()
lx0bsm1f

lx0bsm1f7#

我将这一条作为我对stackoverflow的第一个贡献:

var items: String[] = ["tom", "jeff", "sam"];

const lastOne = [...items].pop();

注意:与不使用spread操作符的pop()不同,这种方法不会从原始数组中删除最后一个元素。

z4bn682m

z4bn682m8#

const arr = [1, 3, 6, 2];
console.log(...arr.slice(-1)); // 2
xjreopfe

xjreopfe9#

有几种方法可以做到这一点。
1.按最后一个元素的索引。

arr[arr.length - 1]

1.使用slice函数:这个函数返回数组中的值,这就是为什么需要访问第0个索引的原因。

arr.slice(-1)[0]

1.使用pop()函数:当你需要获取并删除数组的最后一个元素时,这个方法很有用。元素,最后一个元素将从原始数组中删除。

arr.pop()

1.使用at()函数。注意:这是在ES22中引入的,在旧版本中不起作用

arr.at(-1)

您可以根据自己的偏好选择其中任何一种方法。

相关问题