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.
Array.from({length: 12}, (e, i) => i + 1);
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:
let me = [...new Array(5)].map((x,i)=>i)
// [0,1,2,3,4]
Explanation:
new Array(5)
generates this: [ , , , , ]
[...new Array(5)]
is a shorthand for Array.from(new Array(5))
,
and generates this: [ undefined, undefined, undefined,
undefined, undefined ]
, that is an array of undefined
objects. Yes, undefined
is a value (a primitive one :) ).PS: you can even skip the new
keyword and do:
[...Array(5)].map((x,i)=>i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With