二:變數的解構賦值

來源:互聯網
上載者:User

標籤:json   prototype   ons   var   inf   定義   分享   函數參數   個數   

1)交換變數的值

let x = 1;

let y = 2;

 

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

 

 

知識點:數組的解構賦值。

//數組的解構賦值
let [x,y] = [1,2];
let [x,y] = [2];// x = 2 ,y =undefined;
let [x = 1] = [undefined];x = 1
let [x = 1] = null ; x =null
let [ , , third] = ["foo", "bar", "baz"]; //third = baz;

 

如果等號的右邊不是數組(或者嚴格地說,不是可遍曆的結構,,那麼將會報錯。

// 報錯

let [foo] = 1;

let [foo] = false;

let [foo] = NaN;

let [foo] = undefined;

let [foo] = null;

let [foo] = {};

 

2)從函數返回多個值

函數只能返回一個值,如果要返回多個值,只能將它們放在數組或對象裡返回。有瞭解構賦值,取出這些值就非常方便。

// 返回一個數組

 

function example() {

  return [1, 2, 3];

}

let [a, b, c] = example();

 

// 返回一個對象

 

function example() {

  return {

    foo: 1,

    bar: 2

  };

}

let { foo, bar } = example();

 

3)函數參數的定義

解構賦值可以方便地將一組參數與變數名對應起來。

// 參數是一組有次序的值

function f([x, y, z]) { ... }

f([1, 2, 3]);

 

// 參數是一組無次序的值

function f({x, y, z}) { ... }

f({z: 3, y: 2, x: 1});

//知識點

函數的解構(參數的解構)

function move({x = 0, y = 0} = {}) {

  return [x, y];

}

 

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

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

move({}); // [0, 0]

move(); // [0, 0]

 

4)提取 JSON 資料

解構賦值對提取 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]

 

知識點:對象的解構

對象的解構與數組有一個重要的不同。數組的元素是按次序排列的,變數的取值由它的位置決定;而對象的屬性沒有次序,變數必須與屬性同名,才能取到正確的值。

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

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

baz // "aaa"

foo // error: foo is notdefined

 

上面代碼中,foo是匹配的模式,baz才是變數。真正被賦值的是變數baz,而不是注意,這時p是模式,不是變數,因此不會被賦值。如果p也要作為變數賦值,可以寫成下面這樣。

let obj = {

  p: [

    ‘Hello‘,

    { y: ‘World‘ }

  ]

};

 

let { p, p: [x, { y }] } = obj;

x // "Hello"

y // "World"

p // ["Hello",{y: "World"}]

模式foo。

 

 

預設值生效的條件是,對象的屬性值嚴格等於undefined。

var {x = 3} = {x: undefined};

x // 3

 

var {x = 3} = {x: null};

x // null

 

(5)數值和布爾值的解構賦值

let {toString: s} = 123;

s === Number.prototype.toString // true

 

let {toString: s} = true;

s === Boolean.prototype.toString // true

解構賦值的規則是,只要等號右邊的值不是對象或數組,就先將其轉為對象。由於undefined和null無法轉為對象,所以對它們進行解構賦值,都會報錯。

let { prop: x } = undefined; // TypeError

let { prop: y } = null; // TypeError

 

二:變數的解構賦值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.