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

pit*_*las 33 javascript typescript

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

Swa*_*rmp 60

自 2021 年 7 月起,浏览器开始支持at()数组方法,该方法允许使用以下语法:

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

// shows 3
alert(arr.at(-1)); 
Run Code Online (Sandbox Code Playgroud)

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

编辑:这是可用的typescript@4.5.4

  • 就是现在!https://github.com/microsoft/TypeScript/issues/45512#issuecomment-1004034848 (7认同)
  • .at 方法还有一个额外的优点,如果您的索引不包含在数组中,则可以在类型中包含 undefined 。https://www.typescriptlang.org/play?target=9&ts=4.6.2#code/MYewdgzgLgBFDuIAyBTKUUCcIwLwwG0ByAQSIBoYiAhIgXQG4BYAKFYHp2ZRJYoALAJaYAJqnRYAXDGiZBYAOase0OENHiMmPHESasEAgCZGrDlxV91YtFpJRps+ QpgAfGAFcwIlADN5KCLK4KoCwjYSmPY6CMi2BgB0AIZQABRGAJRAA (3认同)

Shy*_*yju 57

您可以通过索引访问数组元素.数组中最后一个元素的索引将是array-1的长度(因为索引基于零).

这应该工作.

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

alert(items[items.length-1])
Run Code Online (Sandbox Code Playgroud)

是一个工作样本.

  • 这对我来说并不像是一种"符号". (8认同)

use*_*828 31

这是另一种尚未提及的方式:

items.slice(-1)[0]
Run Code Online (Sandbox Code Playgroud)

  • @Loop slice(-1) 不会创建所有数组的副本。它将仅将最后一个元素复制到新数组中。我确实相信这是一个简洁的解决方案。这是当我们每次创建一个包含一个元素的一次性数组只是为了获取其元素时不会过度调用时的最佳解决方案。问题不大,但无论如何都是不必要的。 (5认同)

小智 30

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

array.pop()
Run Code Online (Sandbox Code Playgroud)

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

  • 如果没有必要的话,我们的目标是不修改数据结构。一般来说,我们应该努力实现不变性,仅仅为了访问而修改结构是不明智的。 (3认同)
  • 也可能会发出警告,因为“类型'undefined'不能分配给类型'字符串'” (2认同)

Jay*_*yme 9

这是汇总在一起的选项,适合像我这样迟到的人。

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]
Run Code Online (Sandbox Code Playgroud)


Pet*_*cek 6

如果您更频繁地需要此调用,则可以全局声明它:

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

然后你可以打电话

items.last()
Run Code Online (Sandbox Code Playgroud)


Jua*_*ero 5

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

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

const lastOne = [...items].pop();
Run Code Online (Sandbox Code Playgroud)

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

  • 哎呀!这正在创建数组的全新副本。所以表现几乎是相当糟糕的。 (2认同)