简体   繁体   中英

spread operator in javascript

In the below code,

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

Is spread operator( ... ) unpacking the array and providing 3 values 0, 1, 2?

Yes, as per the page that contains the example you posted:

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

Running the following through an ES6 transpiler :

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

produces:

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

which logs 0 1 2 , showing it has expanded the args array.

Yes, that's exactly what the spread operator does.

It is the equivalent of replacing the identifier containing the iterable with an comma seperated list of values that are the output of iterating the iterable.

In your case, the iterable is an array, and the equivalent is 0, 1, 2 .

Had the iterable been the output of a generator function it would be the same:

function* f1() {
  yield 1;
  yield 2;
  yield 3;
}

var a = [...f1()];
// the above is IDENTICAL to [1, 2, 3]

A powerful use of the operator is when values are not "static" like this:

function* f2(totalCount) {
  let count= 1;
  while(totalCount-- > 0) {
    yield count++;
  }
}

var b = [...f2(5)];
// b is equal to [1, 2, 3, 4, 5]

... is known as Spread/Rest operator depending upon how and where it is used.

What does spread operator do? The spread operator allows an expression to be expanded in places where multiple elements/variables/arguments are expected.

Before ES6, arguments is an array like object, corresponds to the arguments passed to a function. Here is a quick look at its use:

(function(a, b, c){
   console.log(arguments);
})(1, 2, 3);
Output would be [1,2,3].

In ES6, the same can be written as:

function getSum(x, y, z){
   console.log(x+y+z);
}

can call either of two ways:

getSum(...[10,20,30]);

or

var argArr = [10,20,30];
getSume(...argArr);

We have put ... in front of array, so it spread the elements of array into individual values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM