at method

This commit is contained in:
Ilya Kantor 2022-04-14 06:08:46 +03:00
parent 58ef96a61a
commit 61f79f481c

View file

@ -92,6 +92,38 @@ let fruits = [
The "trailing comma" style makes it easier to insert/remove items, because all lines become alike.
````
## Get last elements with "at"
[recent browser="new"]
Let's say we want a last element of the array.
Some programming languages allow to use negative indexes for the same purpose, like `fruits[-1]`.
Although, in JavaScript it won't work. The result will be `undefined`.
We can explicitly calculate the last element index and then access it, using `fruits[fruits.length - 1]`:
```js run
let fruits = ["Apple", "Orange", "Plum"];
alert( fruits[fruits.length-1] ); // Plum
```
A bit cumbersome, isn't it? We need to write the variable name twice.
Luckily, there's a shorter syntax: `fruits.at(-1)`:
```js run
let fruits = ["Apple", "Orange", "Plum"];
// same as fruits[fruits.length-1]
alert( fruits.at(-1) ); // Plum
```
In other words, `arr.at(i)`:
- is exactly the same as `arr[i]`, if `i >= 0`.
- for negative values of `i`, it steps back from the end of the array.
## Methods pop/push, shift/unshift
@ -138,6 +170,8 @@ In computer science the data structure that allows this, is called [deque](https
alert( fruits ); // Apple, Orange
```
Both `fruits.pop()` and `fruits.at(-1)` return the last element of the array, but `fruits.pop()` also modifies the array by removing it.
`push`
: Append the element to the end of the array: