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:
@ -439,7 +473,7 @@ Let's recall the rules:
- If one of the arguments of `==` is an object, and the other one is a primitive, then the object gets converted to primitive, as explained in the chapter <info:object-toprimitive>.
- ...With an exception of `null` and `undefined` that equal `==` each other and nothing else.
The strict comparison `===` is even simpler, as it doesn't convert types.
The strict comparison `===` is even simpler, as it doesn't convert types.
So, if we compare arrays with `==`, they are never the same, unless we compare two variables that reference exactly the same array.
@ -459,7 +493,7 @@ alert( 0 == [] ); // true
alert('0' == [] ); // false
```
Here, in both cases, we compare a primitive with an array object. So the array `[]` gets converted to primitive for the purpose of comparison and becomes an empty string `''`.
Here, in both cases, we compare a primitive with an array object. So the array `[]` gets converted to primitive for the purpose of comparison and becomes an empty string `''`.
Then the comparison process goes on with the primitives, as described in the chapter <info:type-conversions>: