minor fixes
This commit is contained in:
parent
ef714886a4
commit
3a3086b0e0
1 changed files with 12 additions and 10 deletions
|
@ -122,21 +122,23 @@ for (let [key, value] of user) {
|
||||||
```
|
```
|
||||||
````
|
````
|
||||||
|
|
||||||
### Swap variables
|
```smart header="Swap variables trick"
|
||||||
|
A well-known trick for swapping values of two variables:
|
||||||
It is also possible to use destructuring assignment to easily swap variables
|
|
||||||
|
|
||||||
```js run
|
```js run
|
||||||
let a = "1";
|
let guest = "Jane";
|
||||||
let b = "2";
|
let admin = "Pete";
|
||||||
alert(`${a}, ${b}`); // 1, 2
|
|
||||||
|
|
||||||
[a, b] = [b, a];
|
// Swap values: make guest=Pete, admin=Jane
|
||||||
alert(`${a}, ${b}`); // 2, 1: successfully swapped!
|
[guest, admin] = [admin, guest];
|
||||||
|
|
||||||
|
alert(`${guest} ${admin}`); // Pete Jane (successfully swapped!)
|
||||||
```
|
```
|
||||||
|
|
||||||
The trick is that `a` and `b` values are assigned to a new array, from which `a` and `b` take their new values.
|
Here we create a temporary array of two variables and immediately destructure it in swapped order.
|
||||||
This is much easier than using a temporary value to store a value until one of the variables is assigned the new value, then assign the temporary value to the other variable.
|
|
||||||
|
We can swap more than two variables this way.
|
||||||
|
```
|
||||||
|
|
||||||
### The rest '...'
|
### The rest '...'
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue