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
Shy*_*yju 57
您可以通过索引访问数组元素.数组中最后一个元素的索引将是array-1的长度(因为索引基于零).
这应该工作.
var items: String[] = ["tom", "jeff", "sam"];
alert(items[items.length-1])
Run Code Online (Sandbox Code Playgroud)
这是一个工作样本.
use*_*828 31
这是另一种尚未提及的方式:
items.slice(-1)[0]
Run Code Online (Sandbox Code Playgroud)
小智 30
如果之后不需要数组,可以使用
array.pop()
Run Code Online (Sandbox Code Playgroud)
但是这会从数组中删除元素!
这是汇总在一起的选项,适合像我这样迟到的人。
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)
如果您更频繁地需要此调用,则可以全局声明它:
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)
我将把这个作为我对 stackoverflow 的第一个贡献:
var items: String[] = ["tom", "jeff", "sam"];
const lastOne = [...items].pop();
Run Code Online (Sandbox Code Playgroud)
注意:与pop()
不使用扩展运算符不同的是,这种方法不会从原始数组中删除最后一个元素。