JavaScript Array at()
- Mchezo wa kuelekea mababu new Array()
- Mchezo wa kufikia nne concat()
- Rudia kichwa chao Mwongozo wa JavaScript Array wa Matokeo
Definition and usage
at()
method returns the element at the specified index position in the array.
at()
The method is similar to []
has the same effect.
Since March 2022,at()
The method is supported in all modern browsers.
Note
Many programming languages allow the use of negative indices (such as [-1]) to access the end elements of objects/arrays/strings.
In JavaScript, this is not possible because []
Used to access arrays and objects. obj[-1] refers to the value of the key -1, not the last property of the object.
at()
The method was introduced in ES2022 to solve this problem.
Instance
Example 1
Get the third element of the fruits array:
const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits.at(2);
Example 2
Use [] to get the third element of the fruits array:
const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits[2];
Example 3
Get the first element of the fruits array:
const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits.at();
Example 4
Get the last element of the fruits array:
const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits.at(-1);
Syntax
array.at(index)
Parameter
Parameter | Description |
---|---|
index |
Optional. The index (position) of the array element to return. Default value is 0. -1 returns the last element. |
Return value
Type | Description |
---|---|
The element at the given position (index) in the array. |
Browser support
Since March 2022, JavaScript array at()
The method is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome 92 | Edge 92 | Firefox 90 | Safari 15.4 | Opera 78 |
April 2021 | July 2021 | July 2021 | March 2022 | August 2021 |
- Mchezo wa kuelekea mababu new Array()
- Mchezo wa kufikia nne concat()
- Rudia kichwa chao Mwongozo wa JavaScript Array wa Matokeo