javascript - How does `new Array(5).map()` work? -


i've discovered mapping uninitialised array doesn't seem work expect. code:

function hellomap(value, index) {      return "hello " + index;  }    console.clear();    var initialarray = array.apply(null, new array(5));    console.log("array initialised apply:");  console.log(initialarray);  console.log(initialarray.map(hellomap));    var normalarray = new array(5);    console.log("array constructed normally");  console.log(normalarray);  console.log(normalarray.map(hellomap));
.as-console-wrapper {    max-height: 100% !important;  }

i different results despite first output each array being [undefined, undefined, undefined, undefined, undefined].

the fact different results implies undefined in these 2 arrays in fact different. in first suspect array has 5 items in, each 1 undefined. in second array 5 items long there nothing, not undefined in there...

it's bit confusing.

can explain me?

array.apply(null, array(5)) fills array (or array-like object) pass second argument value of first argument pass in, can seen in mdn docs.

new array(5) initializing array it's length property set argument of 5. again, can seen in mdn docs:

if argument passed array constructor integer between 0 , 232-1 (inclusive), returns new javascript array length property set number (note: implies array of arraylength empty slots, not slots actual undefined values).


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -