P粉5459106872023-09-05 10:12:18
The JavaScript parser determines this by analyzing the grammatical context in which the three dots appear.
It will consider whether these 3 points are used with array literals, function calls or function parameters.
For spread operator: When 3 dots are used in array literals and function calls, it is considered a spread operator.
For Remaining Parameter Operator: When 3 dots are used in the parameters of a function definition, it is considered as the remaining parameter operator.
P粉5494120382023-09-05 09:23:13
...
is not an operator. It is the main syntax, just like ()
in the for
statement (they are part of the for
syntax, not instances of the grouping operator) . Operators don't work like spread and rest syntax.
The parser knows which one you are using because of the position in which you are using it, because only one of each position is valid and the other is invalid. For example:
// 1 const [first, ...rest] = someArray; // 2 const { a, ...others } = someObject; // 3 function example(p1, ...others) { // ... }
...it's obvious that you are using remainder syntax in both cases, since it is used in destructuring patterns (1 and 2) and in argument lists (3).
And for:
// 1 const x = [...someIterable]; // 2 const o = { ...someObject }; // 3 example(...someIterable);
...it's obviously expansion, not remainder, since you use it in array literals (1), object literals (2), and parameter lists of function calls (3).