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

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

    I googled it for you, and the first result had a great example:

    Array.of(...items)

    If you want to turn several values into an array, you should always use an array literal, especially since the array constructor doesn’t work properly if there is a single value that is a number (more information on this quirk):

    new Array(3, 11, 8)
    // => [ 3, 11, 8 ]
    new Array(3)
    // => [ , ,  ,]
    new Array(3.1)
    // => RangeError: Invalid array length
    

    But how are you supposed to turn values into an instance of a sub-constructor of Array then? This is where Array.of() helps (remember that sub-constructors of Array inherit all of Array’s methods, including of()).

    class MyArray extends Array {
        ...
    }
    console.log(MyArray.of(3, 11, 8) instanceof MyArray); // true
    console.log(MyArray.of(3).length === 1); // true
    

    It's also worth noting that Array.of() also preserves Array's API compatibility with TypedArray. With TypedArray (Int32Array, UInt32Array, etc.), of() is very useful. From MDN:

    Uint8Array.of(1);            // Uint8Array [ 1 ]
    Int8Array.of("1", "2", "3"); // Int8Array [ 1, 2, 3 ]
    Float32Array.of(1, 2, 3);    // Float32Array [ 1, 2, 3 ]
    Int16Array.of(undefined);    // IntArray [ 0 ]
    

提交回复
热议问题