作者PsMonkey (痞子军团团长)
看板Translate-CS
标题[翻译] ES6 的 destructuring 与 forEach()
时间Wed Mar 13 10:59:35 2013
原文网址:
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