spread operator in javascript

后端 未结 3 617
甜味超标
甜味超标 2021-01-17 03:28

In the below code,

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

Is spread operator(...) unpacki

3条回答
  •  孤城傲影
    2021-01-17 04:07

    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]
    

提交回复
热议问题