Making an array - why is it different?

consider that I declare two variables like this (executed in REPL, with node v7.7.2), which I expect to be arrays:

var x = Array(4) var y = Array.from({length: 4}) 

then the following should work identically, but it is not:

 x.map(Math.random) [ , , , ] y.map(Math.random) [ 0.46597917021676816, 0.3348459056304458, 0.2913995519428412, 0.8683430009997699 ] 

when searching, it seems that x and y are both identical:

 > typeof x 'object' > typeof y 'object' > Array.isArray(x) true > Array.isArray(y) true > x.length 4 > y.length 4 > typeof x[0] 'undefined' > typeof y[0] 'undefined' 

so why the difference?

+7
javascript
source share
3 answers

For the first three outputs, Array#map works.

It is not called for missing array elements (that is, indexes that have never been set, that have been deleted, or that have never been assigned a value).

The ECMA 262 standard for Array.from describes a construction with a length for a new array (point 7 ff).

 var x = Array(4), y = Array.from({ length: 4 }), arrayX = x.map(Math.random), arrayY = y.map(Math.random), z = Array.from({ length: 4 }, Math.random); console.log(x); console.log(y); console.log(arrayX); console.log(arrayY); console.log(z); 
+2
source share

Actually, it should not have the same results for both cases. See here the Array instruction:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with the length property specified by that number ( Note: this means that the array is of massive length intervals, not slots with actual undefined values ). If the argument is any other number, a RangeError exception is thrown.

And here is the Array.from() method

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from

Check the example below on the page:

 // Generate a sequence of numbers // Since the array is initialized with `undefined` on each position, // the value of `v` below will be `undefined` Array.from({length: 5}, (v, i) => i); // [0, 1, 2, 3, 4] 
+4
source share

An array created with array (4) is not renamed with .map (), while Array.from ({length: 4}) is repeated. A more complete explanation can be found in the JavaScript "new Array (n)" and "Array.prototype.map" weirdness , you can check this with.

 x.map((f,i) => console.log(i)) vs. y.map((f,i) => console.log(i)) 
+1
source share

All Articles