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

后端 未结 4 2042
长发绾君心
长发绾君心 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:08

    Array.of([elem1], [elem2], ...)
    

    returns elem1, elem2, etc. in an array.

    equivalent to :

    Array.of = function() {
        return [].slice.call( arguments );
    };
    

    example:

     Array.of("red", "green", "blue")
    
        [ 'red', 'green', 'blue' ]
    

    When you need a constructor function (e.g. to pass it to another function) for arrays, this method is useful. That method lets you avoid a potential pitfall of the Array constructor function: If it has several arguments, it behaves like an array literal. If it has a single argument, it creates an empty array of the given length.

     new Array(3, 4, 5)
        [ 3, 4, 5 ]
        new Array(3)
        []
    

    Here is a link to six new array methods added in ECMAScript for futher refernce.

提交回复
热议问题