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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:42:07  来源:igfitidea点击:

TypeScript/JavaScript forEach call

typescript

提问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.forEachtakes three arguments, element, index, array, so sis 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 validatorsis 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 手册中查看此示例:

example

例子