let a = [1,2,3]; let b = [0, ...a, 4]; // [0,1,2,3,4] let obj = { a: 1, b: 2 }; let obj2 = { ...obj, c: 3 }; // { a:1, b:2, c:3 } let obj3 = { ...obj, a: 3 }; // { a:3, b:2 }
let a = [1,2,3]; let [b, ...c] = a; b; // 1 c; // [2,3]
或者這樣寫javascript
let a = [1,2,3]; let [b, ...[c,d,e]] = a; b; // 1 c; // 2 d; // 3 e; // undefined //************************* //或者這樣寫 function test(a, ...rest){ console.log(a); // 1 console.log(rest); // [2,3] } test(1,2,3)
當遇到長度不匹配時java
let array = [1, 2, 3, 4, 5]; const { x, y, ...z } = array; // 其中z=[3, 4, 5],注意若是因爲array的length不足以完成析構,則會致使z爲[] 對象: let obj = { name: 'zhangsan', age: 30, city: 'shenzhen' }; const {name, ...others} = obj; console.log(name); // 'zhangsan' console.log(others); // {age: 30, city: 'shenzhen'}
2.=>函數
<!-- 單行註釋 --> 遞增/減的操做符 <= 小於等於 => ?
// ES5 var selected = allJobs.filter(function (job) { return job.isSelected(); }); // ES6 var selected = allJobs.filter(job => job.isSelected());
不難看出:當須要編寫一個簡單的單一參數函數時,能夠採用箭頭函數來書寫,標識名=>表達式。這樣就能夠省卻function和return的輸入,還有括號,分號等。this
// ES5 var total = values.reduce(function (a, b) { return a + b; }, 0); // ES6 var total = values.reduce((a, b) => a + b, 0);
/ ES5 $("#confetti-btn").click(function (event) { playTrumpet(); fireConfettiCannon(); }); //ES6的寫法爲: [js] view plaincopy // ES6 $("#confetti-btn").click(event => { playTrumpet(); fireConfettiCannon(); });
//以前是這麼寫的,由於this有做用域限制 { ... addAll: function addAll(pieces) { var self = this; _.each(pieces, function (piece) { self.add(piece); }); }, ... } //如今能夠這樣寫 // ES6 { ... addAll: function addAll(pieces) { _.each(pieces, piece => this.add(piece)); }, ... }
特別注意:spa