js的結構賦值


1.結構賦值

變量聲明並賦值時的解構

var foo = ["one", "two", "three"]; var [one, two, three] = foo; console.log(one); // "one" console.log(two); // "two" console.log(three); // "three"

變量先聲明后賦值時的解構

 

var a, b; [a, b] = [1, 2]; console.log(a); // 1 console.log(b); // 2
默認值(為了防止從數組中取出一個值為undefined的對象,可以在表達式左邊的數組中為任意對象預設默認值)
var a, b; [a=5, b=7] = [1]; console.log(a); // 1 console.log(b); // 7

交換變量

 

var a = 1; var b = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); // 1

解析一個從函數返回的數組

function f() { return [1, 2]; } var a, b; [a, b] = f(); console.log(a); // 1 console.log(b); // 2

忽略某些返回值

function f() { return [1, 2, 3]; } var [a, , b] = f(); console.log(a); // 1 console.log(b); // 3 也可以忽略全部 [,,] = f();

將剩余數組賦值給一個變量

 

var [a, ...b] = [1, 2, 3]; console.log(a); // 1 console.log(b); // [2, 3]

 

注意:如果剩余元素右側有逗號,會報異常
var [a, ...b,] = [1, 2, 3]; // SyntaxError: rest element may not have a trailing comma
 

解構對象

 

基本賦值

 

var o = {p: 42, q: true}; var {p, q} = o; console.log(p); // 42 console.log(q); // true

無聲明賦值

var a, b; ({a, b} = {a: 1, b: 2});

注意:賦值語句周圍的圓括號 ( ... ) 在使用對象字面量無聲明解構賦值時是必須的。

{a, b} = {a: 1, b: 2} 不是有效的獨立語法,因為左邊的 {a, b} 被認為是一個塊而不是對象字面量。

然而,({a, b} = {a: 1, b: 2}) 是有效的,正如 var {a, b} = {a: 1, b: 2}

你的 ( ... ) 表達式之前需要有一個分號,否則它可能會被當成上一行中的函數執行。

給新的變量名賦值

var o = {p: 42, q: true}; var {p: foo, q: bar} = o; console.log(foo); // 42 console.log(bar); // true 

默認值(變量可以先賦予默認值。當要提取的對象對應屬性解析為 undefined,變量就被賦予默認值。)

var {a = 10, b = 5} = {a: 3}; console.log(a); // 3 console.log(b); // 5

給新的變量命名並提供默認值(一個屬性可以同時 1)從一個對象解構,並分配給一個不同名稱的變量 2)分配一個默認值,以防未解構的值是 undefined。)

var {a:aa = 10, b:bb = 5} = {a: 3}; console.log(aa); // 3 console.log(bb); // 5

對象解構中的 Rest

let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40} a; // 10 b; // 20 rest; // { c: 30, d: 40 }

從作為函數實參的對象中提取數據

function userId({id}) { return id; } function whois({displayName: displayName, fullName: {firstName: name}}){ console.log(displayName + " is " + name); } var user = { id: 42, displayName: "jdoe", fullName: { firstName: "John", lastName: "Doe" } }; console.log("userId: " + userId(user)); // "userId: 42" whois(user); // "jdoe is John"
 
 
 

 




 

 





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM