Вопрос

I'm trying to get myself around the insights of JavaScript, currently learning it.

At arrays, I've been reading that the followng is an anti-pattern :

var a = new Array("a", "b", "c");

and the the following, is not :

var a = ["a", "b", "c"];

I'm often having hard times with understanding , because I'm tempted to make analogy with altough, I shouldn't! Could you please explain me why is this?

Это было полезно?

Решение

There are at least three reasons people argue you should use the literal syntax ([...]) rather than the array constructor:

  1. The symbol Array can be shadowed (someone can give it a different meaning in a given scope), the literal cannot.

  2. The literal is shorter and, some would argue, clearer.

  3. The Array constructor has a funny API:

    • If you only give it one argument, then

      • If that argument is a whole number, it uses that argument to set length. So new Array(10) creates an empty array with a length of 10.¹
      • If the argument isn't a number, it uses that argument as the only element in the array. So new Array("10") creates an array with one element ("10") because "10" isn't a number.
      • If the argument is a fractional number, it's an error. So new Array(1.1) fails with "invalid array length" or similar.
    • If you give it more than one argument, it creates an array with that many elements (even if the first argument is a whole number). So new Array(10, 20) creates an array with two elements (10 and 20).

This varying API is defined in this part of the spec.


¹ "...an empty array with a length of 10" That may seem like a strange sentence — how can it be empty and have a length of 10?! — but that's how JavaScript's "arrays" work. You could say they're sparse arrays. Or you could say they aren't really arrays at all. (This is true of the standard Array; the new typed arrays, Int32Array and such, are genuine arrays.)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top