SoFunction
Updated on 2025-04-09

Detailed explanation of the use and precautions of ES6 extension operators

Extended operatorsspread syntax Also known as the expansion syntax, the writing method is..., as the name suggests, it is actually a syntax used to expand strings, arrays and objects. It can be used to express arrays orstringExpand at the syntax level; you can also press the object expression when constructing a literal objectkey-value Expand in a way. Commonly used syntax is as follows:

//Function call:myFunction(...iterableObj);

//Literal array construct or string:[...iterableObj, '4', ...'hello', 6];

// When constructing a literal object, cloning or copying attributes (new features added to the ECMAScript 2018 specification):let objClone = { ...obj };

Using an extension operator when calling a function is equivalent to using

function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(...args);

//Equivalent tofunction myFunction(x, y, z) {}
var args = [0, 1, 2];
(null, args);

andapplyThe difference is that we can not only put all the parameters into an array, but also expand only a few of them with the extension operator, and we can call the extension operator multiple times again.

function myFunction(a, b, c, d, e) {
  (a, b, c, d, e); //-1 0 1 2 3
  (arguments); //[Arguments] { '0': -1, '1': 0, '2': 1, '3': 2, '4': 3 }
}
var args = [0, 1];
myFunction(-1, ...args, 2, ...[3]);

usenewWhen calling the constructor with keywords, you cannot directly add the array.applyWays of (applyExecute the call[[Call]] , not construct[[Construct]]). With the expansion syntax, it is very simple to expand an array into a constructor parameter:

var dateFields = [1970, 0, 1]; // January 1, 1970var d = new Date(...dateFields);

If you want to achieve the same effect without using the extension operator, we must wrap the constructor with a function and put the new constructor intoprototypeSet as an instance of the original constructor, use()(This is mainly for the purpose of modifying the new constructor prototype not to affect the original constructor prototype, use it directlyIt can also be implemented as a prototype of the new constructor).

function applyAndNew(constructor, args) {
  function partial() {
    return (this, args);
  }
  if (typeof  === 'object') {
     = ();
  }
  return partial;
}

function myConstructor() {
  (': ' + );
  (arguments);
  this.prop1 = 'val1';
  this.prop2 = 'val2';
}

var myArguments = ['hi', 'how', 'are', 'you', 'mr', null];
var myConstructorWithArguments = applyAndNew(myConstructor, myArguments);

(new myConstructorWithArguments());
// (in myConstructor constructor): : 6// (in myConstructor constructor): ["hi", "how", "are", "you", "mr", null]// (in "new myConstructorWithArguments"): {prop1: "val1", prop2: "val2"}

Of course, the most common ones are used on the literal array. When there is no expansion syntax, you can only use push, splice, concat and other methods in combination to turn existing array elements into part of the new array. With the expansion syntax, literally, constructing new arrays becomes easier and more elegant:

var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes'];
// ["head", "shoulders", "knees", "and", "toes"]

Can be used to implement shallow copying of arrays:

var arr = [1, 2, 3];
var arr2 = [...arr]; // like ()
(4);

// arr2 becomes [1, 2, 3, 4]// arr not affected

Connect multiple arrays:

var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
var arr3 = [...arr1, ...arr2];

The extension operator can also enumerate all existing objects (enumerable) attribute is copied to the newly constructed object. This method is a shallow copy, and can be copiedSymbolAttributes, but do not contain properties and methods on the prototype. If multiple objects are copied at the same time, the subsequent objects will overwrite the properties of the previous objects with the same name.

var obj1 = { foo: 'bar', x: 42, [Symbol('a')]: 123 };
var obj2 = { foo: 'baz', x: 100, y: 13 };

var clonedObj = { ...obj1 };
(clonedObj); //{ foo: 'bar', x: 42, [Symbol(a)]: 123 }

var mergedObj = { ...obj1, ...obj2 };
(mergedObj); //{ foo: 'baz', x: 100, y: 13, [Symbol(a)]: 123 }

The nature of the method and Similar, but() The function will triggersetters, and the expansion syntax does not.

Things to note

  1. When using expansion syntax in arrays or function parameters, the extension operator can only be used for iterable objects.
  2. Only when the function is called can the extension operator be placed in parentheses, otherwise an error will be reported.
  3. Only used in function calls, literal arrays (can expand strings in arrays), literal objects.
  4. When used for deconstructing assignment of arrays, the extension operator can only be in the last one.
  5. The expanded object can be any iterable object.

Remaining parameters

The remaining parameter syntax allows us to represent an uncertain number of parameters as an array. If the last named parameter of the function is prefixed with ..., it becomes a true array of remaining parameters, from 0 (including) toThe element (excluded) is provided by the actual parameters passed to the function.

Remaining syntax(Rest syntax) It looks exactly the same as the expansion syntax, the difference is that the remaining parameters are used to deconstruct arrays and objects. In a sense, the residual syntax is the opposite of the expansion syntax: the expansion syntax expands an array into each element, while the residual syntax collects multiple elements and "condenses" it into a single element. Extension operators are used in function calls, while remaining parameters are used in function declarations.

There are three main differences between the remaining parameters and arguments objects:

  • The remaining parameters only contain those actual parameters that do not have corresponding formal parameters, andargumentsThe object contains all the actual parameters passed to the function.
  • argumentsThe object is not a real array, and the remaining parameters are real Array instances, which means you can use all array methods directly on it, such assortmapforEachor pop
  • arguments The object also has some additional properties (such as the callee property).

If there is a comma to the right of the remaining parameters (including in the deconstructed assignment), a SyntaxError will be thrown because the remaining elements must be the last parameter of the function or the last element of the array.

The above is a detailed explanation of the ES6 extension operator. For more information about ES6 extension operators, please follow my other related articles!