What is the use case for Javascript's (ES6) Array.of()?

后端 未结 4 2045
长发绾君心
长发绾君心 2020-12-06 03:39

I came across the new Array.of() method that\'s been finalized in ES6, and I was wondering when one might use:

var a = Array.of(\'foo\', \'bar\');

4条回答
  •  情深已故
    2020-12-06 04:15

    instantiating an Array with a number creates an array with that many slots.

    new Array(2);
    > [undefined x 2]
    

    instantiating using Array.of creates an array with those elements.

    Array.of(2)
    > [2]
    

    The point of Array.of is to solve the issue where you want to pass a type around that gets constructed later, which in the special case of array is problematic when it receives a single argument. For instance:

    function build(myItem, arg){
      return new myItem(arg);
    }
    

    Which would give:

    console.log(build(Array, 2));
    > [undefined x 2]
    // ??? Can't pass the literal definition:
    //console.log(build([, 1))
    console.log(build(Array.of, 2));
    > [2]
    

    Or to use even more of ES6 as an example:

    var params = [2,3];
    console.log(new Array(...params));
    // [2,3]
    console.log(new Array.of(...params));
    // [2,3]
    params = [2];
    console.log(new Array(...params));
    // [undefined x2]
    console.log(new Array.of(...params));
    // [2]
    

    Array.of consistently does what you expect.

提交回复
热议问题