TypeScript/JavaScript forEach call
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30949404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript/JavaScript forEach call
提问by pitosalas
I am having trouble understanding this bit of code:
我无法理解这段代码:
stringsArray.forEach(s => {
for (var name in validators) {
console.log('"' + s + '" ' +
(validators[name].isAcceptable(s) ?
' matches ' : ' doesnt match ') + name);
}
});
in particular, the s => { ...
part is mysterious. It looks like s is being assigned to the next string in the array on each loop. But what is the =>
part meaning? It's related to lambdas I think, but I am not following.
尤其是那s => { ...
部分是神秘的。看起来 s 被分配给每个循环中数组中的下一个字符串。但是这=>
部分是什么意思?它与我认为的 lambdas 有关,但我没有遵循。
回答by Josh Beam
Yeah it's a lambda (for example, similar to ECMAScript6 and Ruby, as well as some other languages.)
是的,它是一个 lambda(例如,类似于 ECMAScript6 和 Ruby,以及其他一些语言。)
Array.prototype.forEach
takes three arguments, element, index, array
, so s
is just the parameter name being used for element
.
Array.prototype.forEach
接受三个参数,element, index, array
,因此s
只是用于 的参数名称element
。
It'd be like writing this in regular ECMAScript5:
就像用常规的 ECMAScript5 写这个一样:
stringsArray.forEach(function(s) {
for (var name in validators) {
console.log('"' + s + '" ' +
(validators[name].isAcceptable(s) ?
' matches ' : ' doesnt match ') + name);
}
});
In the above example, you didn't show the whole code, so I assume validators
is just a plain object {}
.
在上面的例子中,你没有展示整个代码,所以我假设validators
只是一个普通的 object {}
。
The syntax for the example you gave is actually identical to the ES6 syntax.
您给出的示例的语法实际上与 ES6 语法相同。
Check out this example from the TypeScript handbook:
从TypeScript 手册中查看此示例: