Why are there advantages to using both spread operator and destructuring assignment in function parameters?
P粉775723722
2023-08-16 16:27:57
<p>I keep encountering this syntax, but I'm having trouble understanding what exactly it's doing: </p>
<pre class="brush:php;toolbar:false;">export class SomeClass extends SomeParent {
constructor(...[configuration]) {
// Only reference the "configuration" line of code
}
}</pre>
<p>After trying it in Node REPL, I found that there is no difference between the following two ways of writing: </p>
<pre class="brush:php;toolbar:false;">function foo(...[bar]) { console.log(bar); console.log(arguments) }</pre>
<p>...and...</p>
<pre class="brush:php;toolbar:false;">function foo(bar) { console.log(bar); console.log(arguments) }</pre>
<p>...So what does it do? </p>
It does seem pointless. You need to ask the author of the code what their intentions are in this regard, and they should at least leave a comment.
However, there is actually a slight difference: the remaining parameters do not count towards the function's number of parameters. Therefore,
(function(bar){}).length
is1
and(function(...[bar]){}).length
is0
.