본문 바로가기
Web/JavaScript

[JavaScript] Array Destructuring

by llHoYall 2020. 9. 2.

Array destructuring is a grammar in which multiple values of an array can be easily assigned as variables.

Ordered Assignment

const arr = [1, 2];
const [a, b] = arr;
console.log(`a: ${a}, b: ${b}`);

//=> Result
// a: 1, b: 2

Default Value

const arr = [1];
const [a = 10, b = 20] = arr;
console.log(`a: ${a}, b: ${b}`);

//=> Result
// a: 1, b: 20

The arr has one element, but it tries to assign two variables.

So the first variable a is assigned from arr, and the second variable b is assigned by the default value.

Skip Item

const arr = [1, 2, 3];
const [a, , c] = arr;
console.log(`a: ${a}, c: ${c}`);

//=> Result
// a: 1, c: 3

The second element is skipped and the third element is assigned.

Create a new Array with remaining Elements

const arr = [1, 2, 3, 4, 5];
const [a, b, ...remainedValues] = arr;
console.log(`a: ${a}, b: ${b}`);
console.log(`remained values: ${remainedValues}`);

//=> Result
// a: 1, b: 2
// remained values: 3,4,5

Nested Array

const arr = [
  [11, 12, 13],
  [21, 22, 23],
];
const [[a1, a2, a3], [b1, b2, b3]] = arr;
console.log(`a1: ${a1}, a2: ${a2}, a3: ${a3}`);
console.log(`b1: ${b1}, b2: ${b2}, b3: ${b3}`);

//=> Result
// a1: 11, a2: 12, a3: 13
// b1: 21, b2: 22, b3: 23

'Web > JavaScript' 카테고리의 다른 글

[React] prop-types  (0) 2020.09.02
[JavaScript] Object Destructuring  (0) 2020.09.02
[Electron] Tray  (0) 2020.09.01
[Electron] Global Shortcut  (0) 2020.09.01
[Electron] Menu  (0) 2020.09.01

댓글