看板 Translate-CS 關於我們 聯絡資訊
原文網址:http://www.2ality.com/2013/02/foreach-es6.html 譯文網址:http://blog.dontcareabout.us/ 2013/03/ecmascript-6-destructuring-foreach.html BBS 版以 markdown 撰寫,請見諒 Orz __________________________________________________________________ > # ECMAScript 6 的參數 destructuring 功能與 forEach() # 這篇文章會簡單介紹 ECMAScript 6(以下簡稱 ES6) 的 destructuring、 以及這個功能對 `forEach()` 這個 array method 的好處。 destructuring ------------- ES6 允許你作 destructure(譯註:可翻成解構)的動作: 賦予值的對象可以是一個 pattern, 讓你在賦予值的來源值中找尋這個 pattern 然後以此給值。 下面這個例子在宣告變數時使用 destructuring: > let { first: f, last: l } = { first: 'Jane', last: 'Doe' }; > f 'Jane' > l 'Doe' 下面這個例子是交換 `x` 跟 `y` 的值: [x,y] = [y,x] destructuring 也可以用在參數。 下面這個 function 有兩種參數: 第一種參數是 positional(辨別位置)、 其他的參數是 named(辨別名稱)包在一個叫做 `options object` 裡頭 (就是實際上的第二個參數): function foo(positional, { named1, named2 }) { return [ positional, named1, named2 ]; } 使用這個 function 的方式: > foo(123, { named1: 'abc', named2: 'def' }) [ 123, 'abc', 'def' ] > foo(123, { named2: 'def', named1: 'abc' }) [ 123, 'abc', 'def' ] 兩個參數(`positional` 與 `named`)都可以指定 default 值, 而變成可有可無的參數 [Ref.1]。 destructuring 與 `forEach()` ---------------------------- 在 ES6 當中,destructuring 參數對於 `Array.prototype.forEach()` 是很有用的。 舉個例子: let items = [ ['foo', 3], ['bar', 9] ]; items.forEach(([word, count]) => console.log(word+' '+count)); 上面 `forEach()` 的傳入值是一個 `arrow function`, 這個撰寫 function 表示式的簡潔方式是 ES6 的新功能 [Ref.2]。 array 的 element 也可以是 object: let items = [ {word:'foo', count:3}, {word:'bar', count:9} ]; items.forEach(({word, count}) => console.log(word+' '+count)); object 的 literal { word, count } 是下面這個語法的簡寫: { word: word, count: count } 因此,你也可以把上面的迴圈寫成 items.forEach(({word: w, count: c}) => console.log(w+' '+c)); 備註:ES6 有新的 `for-of` 迴圈也可以用 destructuring [Ref.3]: for ([word, count] of items) { console.log(word+' '+count); } [Ref.1]: http://www.2ality.com/2011/11/keyword-parameters.html [Ref.2]: http://www.2ality.com/2012/04/arrow-functions.html [Ref.3]: http://www.2ality.com/2012/06/for-of-ff13.html -- 錢鍾書: 說出來的話 http://www.psmonkey.org 比不上不說出來的話 Java 版 cookcomic 版 只影射著說不出來的話 and more...... -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.25.16.4