Array.of vs “[ ]”. When to use Array.of over “[ ]”?

后端 未结 3 1434
滥情空心
滥情空心 2020-11-30 08:48

I was doing a bit of reading when I found Array.of.

As per MDN,

The Array.of() method creates a new Array instance with a variable number of argum

3条回答
  •  旧巷少年郎
    2020-11-30 09:09

    Although this method might have been standardized, it does appear to be unsupported in a number of browsers, so using it seems risky and, as you note, pretty much pointless.

    The utility of this function seems to be for cases where you need to declare an array but don't want to assemble it out of parts. That is, you want to be able to pass a number of arguments to some function that then returns an Array.

    If you follow the links to the justification of that method you get this:

    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. In that case, Array will not do the right thing in the one-number-arg case.

    That's basically a way of saying "this function can receive variable length argument lists and will consistently return arrays populated with the correct values", but as in practice that converts an array to...an array, I'm not entirely convinced this thing needs to exist and apparently many browser implementors are of a similar mindset.

    The push for Array.of largely a response to the fact that new Array() behaves inconsistently:

    new Array(2);
    // [ , ] 2-element array that's unpopulated
    
    new Array(1,2);
    // [1,2] 2-element array populated with the provided values
    

    Array.of will always operate like the latter version.

提交回复
热议问题