ES6 對象的解構賦值

基本原則以下:javascript

  • 數組的元素是按次序排列的,變量的取值由它的位置決定;
  • 對象的屬性沒有次序,變量必須與屬性同名,才能取到正確的值。

數組的解構賦值:

let [x, y]= [1, 2];
// x = 1
// y = 2

對象的解構賦值:

let { foo , bar } = { foo: "aaa", bar: "bbb" };
// foo = "aaa"
// bar = "bbb"

可是對象的解構賦值,容許給賦值的變量重命名。java

變量的解構賦值用途不少。react

(1)交換變量的值ajax

let x = 1;
let y = 2;
 
[x, y] = [y, x];

寫法不只簡潔,並且易讀,語義很是清晰json

(2) 從函數返回多個值數組

// 返回一個數組
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一個對象
function example() {
return {
 foo: 1,
 bar: 2
};
}
let { foo, bar } = example();

(3)函數參數的定義async

解構賦值能夠方便地將一組參數與變量名對應起來。函數

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

(4)提取JSON數據ui

解構賦值對提取JSON對象中的數據,尤爲有用。url

let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};
 
let { id, status, data: number } = jsonData;
 
console.log(id, status, number);
// 42, "OK", [867, 5309]

上面代碼能夠快速提取 JSON 數據的值。

(5)函數參數的默認值

jQuery.ajax = function (url, {
  async = true,
  beforeSend = function () {},
  cache = true,
  complete = function () {},
  crossDomain = false,
  global = true,
  // ... more config
}) {
  // ... do stuff
};

指定參數的默認值,就避免了在函數體內部再寫var foo = config.foo || 'default foo';這樣的語句。

(6)遍歷Map結構

任何部署了Iterator接口的對象,均可以用for...of循環遍歷。Map結構原生支持Iterator接口,配合變量的解構賦值,獲取鍵名和鍵值就很是方便。

var 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) {
  // ...
}

(7)輸入模塊的指定方法

加載模塊時,每每須要指定輸入那些方法。解構賦值使得輸入語句很是清晰。

const { SourceMapConsumer, SourceNode } = require("source-map");
// 導入react組件
import {ReactComponent} from './xxxComponent.jsx';

連接:https://www.jianshu.com/p/5fccba8328e3

相關文章
相關標籤/搜索