Javascript 访问 TypeScript 数组的最后一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31277004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access last element of a TypeScript array
提问by pitosalas
Is there a notation to access the last element of an array in TypeScript? In Ruby I can say: array[-1]
. Is there something similar?
是否有一种表示法可以访问 TypeScript 中数组的最后一个元素?在 Ruby 中,我可以说:array[-1]
. 有没有类似的东西?
回答by Shyju
You can access the array elements by it's index. The index for the last element in the array will be the length of the array-1 ( as indexes are zero based).
您可以通过它的索引访问数组元素。数组中最后一个元素的索引将是数组 1 的长度(因为索引从零开始)。
This should work.
这应该有效。
var items: String[] = ["tom", "jeff", "sam"];
alert(items[items.length-1])
Hereis a working sample.
这是一个工作示例。
回答by Fabian Chanton
If you don't need the array afterwards, you could use
如果您之后不需要该数组,则可以使用
array.pop()
But that removes the element from the array!
但这会从数组中删除元素!
回答by user108828
Here is another way which has not yet been mentioned:
这是另一种尚未提及的方式:
items.slice(-1)[0]
回答by Jayme
Here are a the options summarized together, for anyone finding this question late like me.
这是汇总在一起的选项,适合像我这样迟到的人。
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]