Destructuring

解構賦值是一種 JavaScript 運算符號,

可以將陣列或物件中的資料解構出來,

並且賦值給變數

解構陣列

使用 陣列解構 將陣列元素賦給個別變數:

const arr = [1, 2, 3];
const [a, b, c] = arr;

console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

巢狀陣列 也可以解構:

const arr = [1, 2, 3, [4, 5, 6]];
const [a, b, c, [d, e, f]] = arr;

console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
console.log(d); // 4
console.log(e); // 5
console.log(f); // 6

解構物件

使用 物件解構 將物件屬性賦給個別變數:

const obj = {
  name: "John",
  age: 30,
  city: "New York",
};
const { name, age, city } = obj;

console.log(name); // John
console.log(age); // 30
console.log(city); // New York

巢狀物件 也可以解構:

const obj = {
  name: "John",
  age: 30,
  city: "New York",
  cars: {
    car1: "Ford",
    car2: "BMW",
    car3: "Fiat",
  },
};
const { name, age, city, cars } = obj;

console.log(name); // John
console.log(age); // 30
console.log(city); // New York
console.log(cars); // { car1: 'Ford', car2: 'BMW', car3: 'Fiat' }

解構物件並賦予預設值

使用物件解構將物件屬性賦給個別變數,

並且 賦予預設值 :

const obj = {
  name: "John",
  age: 30,
  city: "New York",
};
const { name, age, city, job = "Engineer" } = obj;

console.log(name); // John
console.log(age); // 30
console.log(city); // New York
console.log(job); // Engineer

解構物件並賦予別名

使用物件解構將物件屬性賦給個別變數,

並且 賦予別名 :

const obj = {
  name: "John",
  age: 30,
  city: "New York",
};
const { name: myName, age: myAge, city: myCity } = obj;

console.log(myName); // John
console.log(myAge); // 30
console.log(myCity); // New York