【发布时间】:2015-09-25 10:32:08
【问题描述】:
TypeScript 中是否有访问数组最后一个元素的符号?在 Ruby 中,我可以说:array[-1]。有没有类似的?
【问题讨论】:
标签: javascript typescript
TypeScript 中是否有访问数组最后一个元素的符号?在 Ruby 中,我可以说:array[-1]。有没有类似的?
【问题讨论】:
标签: javascript typescript
您可以通过索引访问数组元素。数组中最后一个元素的索引将是数组 1 的长度(因为索引是从零开始的)。
这应该可行。
var items: String[] = ["tom", "jeff", "sam"];
alert(items[items.length-1])
Here 是一个工作示例。
【讨论】:
如果以后不需要数组,可以使用
array.pop()
但这会从数组中删除元素!
pop 返回T | undefined,因此您需要在实现中注意这一点。
如果您确定总会有一个值,您可以使用非空断言运算符 (!):
var poped = array.pop()
array.push(poped!);
【讨论】:
Type 'undefined' is not assignable to type 'string'
这是另一种尚未提及的方式:
items.slice(-1)[0]
【讨论】:
以下是汇总在一起的选项,适合像我这样迟到的人。
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]
【讨论】:
slice 真的比其他人慢很多吗? pop 也是函数调用。
如果您更频繁地需要此调用,可以全局声明它:
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()
【讨论】:
我将使用这个作为我对 stackoverflow 的第一个贡献:
var items: String[] = ["tom", "jeff", "sam"];
const lastOne = [...items].pop();
注意:与不使用扩展运算符的 pop() 不同,此方法不会从原始数组中删除最后一个元素。
【讨论】:
自 2021 年 7 月起,浏览器开始支持数组的 at() 方法,该方法允许使用以下语法:
const arr: number[] = [1, 2, 3];
// shows 3
alert(arr.at(-1));
我不清楚 TypeScript 将在什么时候开始支持此功能(它现在还不适合我),但我猜它应该很快就会可用。
【讨论】:
const arr = [1, 3, 6, 2];
console.log(...arr.slice(-1)); // 2
【讨论】: