What is the syntax? (found in Angular2)

I don't know if this syntax or character or something else Angular2 to Angular2 or something else ...

but I wonder

what's the syntax ... and how does it work behind the scenes?

 ngOnChanges(...args:any[]) { console.log(args); } 
+6
source share
3 answers

This is a TypeScript rest statement . In this case, this means that there can be any number of arguments of any type; the function will see them as an any array. (JavaScript recently received rest and distribution operators, as well as ES2015, but :any[] in your example tells us that it is TypeScript.)

eg:.

 ngOnChanges('a', 42, null); 

... will show

  ["a", 42, null]

in the console.

Here is a complete example ( live copy ):

 function foo(...args:any[]) { console.log("args.length = " + args.length); args.forEach((arg:any, index:Number) => { console.log("args[" + index + "]: " + arg); }); } foo('a', 42, null); 

exits

  args.length = 3
 args [0]: a
 args [1]: 42
 args [2]: null
+7
source

The syntax of the remaining parameters allows us to represent an indefinite number of arguments as an array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

 function(a, b, ...theArgs) { // ... } 

If the last named function argument has a prefix with ..., it becomes an array whose elements from 0 to theArgs.length are passed by the actual arguments passed to the function.

In the above example, theArgs collected the third argument of the function (because the first maps to a, and the second to b) and all consecutive arguments.

+3
source

This is the ES2015 distribution operator (or the ellipsis operator). This allows you to destruct the array.

For instance:

 function myFunction(x, y, z) { // x = 0, y = 1, z = 2 } var args = [0, 1, 2]; myFunction(...args); 

See this link for more details:

+1
source

All Articles