1. 程式人生 > 其它 >ES6 結構賦值

ES6 結構賦值

物件解構

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

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

使用解構賦值表示式時,如果指定的區域性變數名稱在物件中不存在,那麼這個區域性變數會被賦值為undefined

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

陣列解構

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

在這段程式碼中,我們從colors陣列中解構出了"red"和"green"這兩個值,並分別儲存在變數firstColor和變數secondColor中。在陣列解構語法中,我們通過值在陣列中的位置進行選取,且可以將其儲存在任意變數中,未顯式宣告的元素都會直接被忽略

也可以在陣列解構賦值表示式中為陣列中的任意位置新增預設值,當指定位置的屬性不存在或其值為undefined時使用預設值