最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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');

over:

var b = ['foo', 'bar'],
    c = new Array('foo', 'bar');

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');

over:

var b = ['foo', 'bar'],
    c = new Array('foo', 'bar');
Share Improve this question asked Jul 28, 2015 at 20:24 Alex RossAlex Ross 3,8393 gold badges27 silver badges29 bronze badges 2
  • It just adds syntactic sugar I think. – Wand Maker Commented Jul 28, 2015 at 20:33
  • It is more the brackets that is sugar not so easy to handle as other functions – user985399 Commented May 22, 2019 at 21:38
Add a ment  | 

4 Answers 4

Reset to default 10

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.

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 patibility 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 ]

It basically fixes the Array constructor, which has a special case when you pass it a single number.

From the original proposal:

Array.of provides a constructor that, unlike Array, does not have the special case for new Array(42), which presets length (and hints to implementations to preallocate) but leaves holes in [0, length).

The use-case is when you can't write a literal, because you are passing a function-that-constructs as a funarg, and the eventual caller may pass only one number arg, or several args.

It also does help with subclassing, where it can be used as the "literal form" for instances of your array subclass.

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.

发布评论

评论列表(0)

  1. 暂无评论