此文章爲意譯並不是直譯,可參考具體原文javascript
解構賦值是javascript中的一個表達式語法糖,幫助開發者將數組,對象屬性解構出來而且直接賦值到具體變量上面。java
let a,b,rest; [a,b] = [10,20]; console.log(a);// 10, console.log(b);// 20; [a,b,...rest] = [10,20,30,40,50,60]; console.log(a); // 10 console.log(b); // 20 console.log(rest);// [30,40,50,60]
let a=10,b=20; [a,b]=[b,a]; console.log(a);// 20 console.log(b);// 10;
// 1. 從已有對數組中解構賦值 let foo = ['one','two','three']; let [a,b] = foo; console.log(a); console.log(b); // 2. 從字面量中解構賦值 let [a,b] = [1,2]; // 3. 在解構賦值對時候設置默認值 let [a=5, b=10] = [1]; console.log(a); // 輸出:1 console.log(b); // 輸出:10 // 4. 解構從函數返回對數組 function getArr(){ return [1,2] } let [a,b] = getArr(); // 5. 解構對時候,忽略特殊位置對值 let [a,,b] = [1,2,3]; // 所有忽略 [,,] = [1,2,3]; // 6. 解構對時候將數組的其餘值賦值給變量 let [a,...b] = [1,2,3,4,5]; console.log(a);// 1 console.log(b);// [2,3,4,5]
// 1. 解構對象 let obj = {name:'hello',age:18}; let {name,age} = obj; console.log(name);// hello; console.log(age);// 18 // 2. 解構字面量對象 let name,age; ({name,age} = {name:'hello',age:18});// 結果和上面同樣,注意,這裏爲何須要用`()`包裹起來呢? // 獨立的寫法 let {name,age} = {name:'hello',age:18}; // 3. 解構的時候,設置別名 let obj = {name:'hello',age:18}; let {name:nameA,age:ageA} = obj; console.log(nameA);// hello console.log(ageA);// 18 // 4. 設置默認值,這個和數組解構相似 let obj = {name:'hello',age:18}; let {name='tom',age=20,city='sh'}=obj; console.log(city);// sh // 5. 設置默認值,同時又設置別名 let obj = {n:'hello',age:18}; let {n:name='tom',age:a=19,city:c='sh'} = obj; console.log(name); // hello console.log(a); // 18 console.log(c); // sh // 6. 設置函數參數的默認值 function drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius = 25} = {}) { console.log(size, cords, radius); // do some chart drawing } drawES2015Chart({ cords: {x: 18, y: 30}, radius: 30 });
let data = { title:'objetAdnArray', list:[ { id:1, des:'第一個對象', proList:[] }, { id:2, des:'第二個對象', proList: [] } ] } let { title, list:[{id,des}] } = data; console.log(title); // objetAdnArray console.log(id); // 1 console.log(des); // 第一個對象
var people = [ { name: 'Mike Smith', family: { mother: 'Jane Smith', father: 'Harry Smith', sister: 'Samantha Smith' }, age: 35 }, { name: 'Tom Jones', family: { mother: 'Norah Jones', father: 'Richard Jones', brother: 'Howard Jones' }, age: 25 } ]; for (let {name: n, family: {father: f}} of people) { console.log('Name: ' + n + ', Father: ' + f); } // "Name: Mike Smith, Father: Harry Smith" // "Name: Tom Jones, Father: Richard Jones"
function userId({id}) { return id; } function whois({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"
let key = 'z'; let {[key]:foo} = {z:'this is z'}; console.log(foo); // this is z // 注意,這個用戶很相似對象字面量賦值的用法 let obj = { [key]:'hello' } obj.z // hello
總結:es6提供了許多語法糖,在客戶端使用的時候須要經過進行編譯才能運行,而在服務器端nodejs
已經很好的支持了node