1. 程式人生 > >《深入理解ES6》之解構

《深入理解ES6》之解構

nbsp span 對象 code true 上下文 div 嵌套對象 賦值

結構是一種打破數據解構,將其拆分為更小部分的過程。

對象解構

  對象字面量的語法形式是在一個賦值操作符左邊放置一個對象字面量。

let node={
    type:"indefine",
    name:"foo"
};
let{type,name}=node;

console.log(type);//indefine
console.log(type);//foo

解構賦值

  可以在定義變量之後想要修改它們的值。

let node={
    type:"indefine",
    name:"foo"
},
type="literal",
name
=5; ({type,name}=node); console.log(type);//indefine console.log(type);//foo

  一定要用一對小括號包裹解構賦值語句,JavaScript引擎講一對開放的花括號視為一個代碼塊,而語法規定,代碼塊語句不允許出現在賦值語句左側,添加小括號後可以將快語句轉化為一個表達式,從而實現整個解構賦值的過程。

默認值

  當指定的屬性不存在,這個局部變量會被賦值為undefined,也可以隨意定義一個默認值,在屬性名稱後面添加一個等號和相應的默認值。

let node={
    type:"indefine",
    name:
"foo" } let{type,name,value=true,age}=node; console.log(type);//indefie console.log(type);//foo console.log(value);//true console.log(age);//undefined

為非同名局部變量賦值

  使用解構賦值來聲明變量localType和localName,這兩個變量分別包含node.type和node.name屬性的值。

let node={
    type:"indefine",
    name:"foo"
}
let{type:localType,name:localName,age
=4}=node; console.log(localType);//indefie console.log(localName);//foo console.log(age);//4

嵌套對象解構

    let node={
        type:"indefine",
        name:"foo",
        loc:{
            start:{
                line:1,
                column:2
            },
            end:{
                line:1,
                column:4
            }
        }
    };
    let{loc:{start:localStart}}=node;

    console.log(localStart.line);//1
    console.log(localStart.column);//2
  

  解構模式可以應用於任意層級深度的對象,且每一層都具有同等的功能。

數組解構

  解構賦值,數組解構可以賦值上下文,但不需要用小括號包裹表達式。

let colors=["red","green","blue"],
    firstColor="black",
    secondColor="purple";
[firstColor,secondColor]=colors;
console.log(firstColor);//red

  數組解構可以交換兩個變量的值。

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

  嵌套數組解構與嵌套對象解構的語法類似。

let colors=["red",["green","ligntgreen"],"blue"];
let [firstColor,[secondColor]]=colors;
console.log(firstColor);//red
console.log(secondColor);//green

  可以講不定元素應用到數組解構中。可以將數組中的其余元素賦值給一個特定的變量,也可以實現數組復制的功能。

let colors=["red","green","blue"];
let[firstColor,...restColor]=colors;

console.log(firstColor);//red
console.log(restColor[0]);//green

var fruits=["apple","bannan"];
[...cloneF]=fruits;
console.log(cloneF);//[apple,bannan]

《深入理解ES6》之解構