TypeScript / JavaScript for each call

I find it hard to understand 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 part s => { ... mysterious. It looks like s is assigned to the next line of the array in each loop. But what is the meaning => ? I think this is due to lambdas, but I do not follow.

+8
typescript
source share
1 answer

Yes, this is a lambda (for example, similar to ECMAScript6 and Ruby, as well as some other languages.)

Array.prototype.forEach takes three arguments, element, index, array , so s is just the parameter name used for element .

It will be like writing this file to regular 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 did not specify all the code, so I assume that validators is just a simple {} object.

The syntax for the example you provided is actually identical to the ES6 syntax.

See this example from the TypeScript reference :

example

+12
source share

All Articles