I was trying to use new Array()
constructor with map
in order to create a one-line code that creates a list of elements. Something like this :
let arr = new Array(12).map( (el, i) => {
console.log('This is never called');
return i + 1;
});
Reading docs, the behaviour makes sense.
Basically docs say that callback of map will be executed even for declared undefined values in array, but not for example when creating empty Arrays like the code before.
So this should work :
var arr = new Array(12);
for(let i = 0; i < arr.length ; i++){
arr[i] = undefined;
}
let list = arr.map( (e, i) => {
console.log(i + 1);
return i + 1;
});
So, We also can do something like this :
let newArray = (length) => {
let myArray = new Array(length);
for(let i = 0; i < length; i++) myArray[i] = undefined;
return myArray;
};
console.log( newArray(12).map( (el, i) => i + 1 ) );
So my question. Is there a better/pretty way to do it with map function ?
Thanks in advance!
You can use
Array#from
to create an array having passed length.Section 22.1.3.15 of the spec is getting you, with the last line of
NOTE 1
:This behavior is shared by
filter
,forEach
, and the other functional methods.The array constructor you are calling,
Array(len)
from section 22.1.1.2, will set the length of the array but not initialize the elements. I'm not sure where the spec defines what a missing element is, but the array produced bynew Array(len)
should fit that and so none of the elements will be touched bymap
.If I am not mistaken, you explicitly said that you wanted an answer with new Array constructor.
Here is how to do it. One line, beautiful ES6:
Explanation:
new Array(5)
generates this:[ , , , , ]
[...new Array(5)]
is a shorthand forArray.from(new Array(5))
, and generates this:[ undefined, undefined, undefined, undefined, undefined ]
, that is an array ofundefined
objects. Yes,undefined
is a value (a primitive one :) ).PS: you can even skip the
new
keyword and do:I like this approach because it still works in ES5:
Since
New Array
returns an array that contains "holes", we use apply because apply treats holes as if they were undefined. This spreads undefined across the entire array which makes it mappable.You could use
Array
.apply
with an object with the length in it.