JavaScript: Array Constructor
new Array(args)
-
Same as without
new
. Array()
- Return a empty array.
Array(int_n)
-
int_n is integer. Return a Sparse Array with length int_n.
If int_n is negative, RangeError.
Use together with Array.prototype.fill to fill array.
WARNING:
Array(3)
does not actually create any element in the array at all.// new Array(int) does not create any elements, only sets length const xx = new Array(2); console.log(Object.getOwnPropertyNames(xx)); // [ 'length' ] // compare to, const yy = [undefined, undefined]; console.log(Object.getOwnPropertyNames(yy)); // [ "0", "1", "length" ]
If you create a array by
Array(4)
, then use the array methodmap
to fill in, it doesn't work.// creating array by map this way doesn't work const xx = new Array(3); const yy = xx.map(() => 9); console.log(yy); // [ <3 empty items> ] // expected [9, 9, 9] console.log(yy[0] !== 9);
Array(non_int_x)
-
non_int_x is not a integer. Result is a array with a single element non_int_x.
const xx = Array("a"); console.log(xx); // [ "a" ]
Array(a1, a2 etc)
-
array of items a1, a2, etc.
const xx = Array("a", "b"); console.log(xx); // [ "a", "b" ]