Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access last element of a TypeScript array

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?

like image 489
pitosalas Avatar asked Jul 07 '15 18:07

pitosalas


People also ask

How can you access the last element of the array?

1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.

What is the last element in an array?

The Last element is nothing but the element at the index position that is the length of the array minus-1. If the length is 4 then the last element is arr[3].

How do you get the second last element of array in TypeScript?

To get the second to last element in an array, call the at() method on the array, passing it -2 as a parameter, e.g. arr.at(-2) . The at method returns the array element at the specified index.

How do I find the first and last elements of an array?

The first and last elements are accessed using an index and the first value is accessed using index 0 and the last element can be accessed through length property which has one more value than the highest array index. The array length property in JavaScript is used to set or return the number of elements in an array.


1 Answers

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).

This should work.

var items: String[] = ["tom", "jeff", "sam"];  alert(items[items.length-1]) 

Here is a working sample.

like image 109
Shyju Avatar answered Sep 28 '22 06:09

Shyju