Reputation: 55443
I don't know if this syntax or symbol or whatever belongs to Angular2
or something else...
but I wonder with,
what ...
syntax is and how it works behind the scene?
ngOnChanges(...args:any[])
{
console.log(args);
}
Upvotes: 7
Views: 1676
Reputation: 1074158
It's the TypeScript rest operator. In this case, it means any number of arguments of any type can occur there; the function will see them as an array of any
. (JavaScript recently got rest and spread operators as well, as of ES2015, but the :any[]
in your example tells us this is TypeScript.)
E.g.:
ngOnChanges('a', 42, null);
...would show
["a", 42, null]
in the console.
Here's 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);
outputs
args.length = 3 args[0]: a args[1]: 42 args[2]: null
Upvotes: 8
Reputation: 657198
The rest parameter syntax 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 argument of a function is prefixed with ..., it becomes an array whose elements from 0 to theArgs.length are supplied by the actual arguments passed to the function.
In the above example, theArgs would collect the third argument of the function (because the first one is mapped to a, and the second to b) and all the consecutive arguments.
Upvotes: 3
Reputation: 202146
It's the ES2015 spread operator (or ellipsis operator). This allows to destructuring array.
For example:
function myFunction(x, y, z) {
// x = 0, y = 1, z = 2
}
var args = [0, 1, 2];
myFunction(...args);
See this link for more details:
Upvotes: 1