Hướng dẫn javascript object spread
Spread syntax ( Spread syntax looks exactly like rest syntax. In a way, spread syntax is the opposite
of rest syntax. Spread syntax "expands" an array into its elements, while rest syntax collects multiple elements and "condenses" them into a single element. See rest parameters and rest property. DescriptionSpread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list. There are three distinct places that accept the spread syntax:
Although the syntax looks the same, they come with slightly different semantics. Only iterable objects, like
On the other hand, spreading in object literals enumerates the own properties of the object. For typical arrays, all indices are enumerable own properties, so arrays can be spread into objects.
When using spread syntax for function calls, be aware of the possibility of exceeding the
JavaScript engine's argument length limit. See ExamplesSpread in function callsReplace apply() It is common to use
With spread syntax the above can be written as:
Any argument in the argument list can use spread syntax, and the spread syntax can be used multiple times.
Apply for new operatorWhen calling a constructor with
Spread in array literalsA more powerful array literal Without spread syntax, to create a new array using an existing array as one part of it, the array literal syntax is no longer sufficient and imperative code must be used instead using a combination of
Just like spread
for argument lists, Copy an array
Note: Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays. The same is true with
A better way to concatenate arrays
With spread syntax this becomes:
With spread syntax, this becomes:
Note:
Unlike Spread in object literalsShallow-cloning (excluding prototype) or merging of
objects is possible using a shorter syntax than
Note that
In addition,
You cannot naively re-implement the
In the above example, the spread syntax
does not work as one might expect: it spreads an array of arguments into the object literal, due to the rest parameter. Here is an implementation of
Specifications
Browser compatibilityBCD tables only load in the browser See also |