1. 程式人生 > 實用技巧 >ES6 解構賦值的作用

ES6 解構賦值的作用

概述

es6允許按照一定的模式,從陣列或物件中提取值,給變數進行賦值,稱為解構賦值。

解構賦值在程式碼書寫上簡單易懂,語義清晰明瞭,方便對複雜物件中資料欄位的獲取。

解構模型

在解構中,解構的源,位於解構賦值表示式的右邊,而解構的目標,在解構表示式的左邊。

常見用途

乍一看上面的概述,不太清楚到底是幹嘛的,那,有很多地方可以用到解構,很方便呢又強大,下面舉幾個常用的例子:

字串

var [a,b,c,d,e] = "hello";
console.log(a); // h
console.log(b); // e
console.log(c); // l
console.log(d); // l
console.log(e); // o

  

交換變數的值

let x = 1;
let y = 2;

[x, y] = [y, x];

  

函式

function move({x = 0, y = 0} = {}) {
    console.log([x, y]);
}

move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]

  

從函式返回多個值

// 返回一個數組

function example() {
  return [1, 2, 3];
}
let [a, b, c] = example();

// 返回一個物件

function example() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = example();

  

函式引數的定義

// 引數是一組有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);

// 引數是一組無次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});

  

提取 JSON 資料

let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

let { id, status, data: number } = jsonData;

console.log(id, status, number);
// 42, "OK", [867, 5309]

  

遍歷Map結構

const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');

for (let [key, value] of map) {
  console.log(key + " is " + value);
}
// first is hello
// second is world

  

如果只想獲取鍵名,或者只想獲取鍵值,可以寫成下面這樣。

// 獲取鍵名
for (let [key] of map) {
  // ...
}

// 獲取鍵值
for (let [,value] of map) {
  // ...
}