How to differentiate between spread operator and remainder operator in JavaScript?
P粉022501495
P粉022501495 2023-09-04 11:25:07
0
2
487
<p>The syntax is the same, so how does JavaScript distinguish between the two under the hood? </p> <p>Is it judged based on the data type of the variable being operated on? Or is it based on where the variable is used? Or neither? </p>
P粉022501495
P粉022501495

reply all(2)
P粉545910687

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粉549412038

... 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).

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template