I wrote the following code:
let abcd= Array.from({length:7},(curr,i)=> { console.log(curr,i); i+1;})
console.log(abcd); // returns [undefined *7]
I can't understand why abcd isn't initialized to 1 to 7?
I wrote the following code:
let abcd= Array.from({length:7},(curr,i)=> { console.log(curr,i); i+1;})
console.log(abcd); // returns [undefined *7]
I can't understand why abcd isn't initialized to 1 to 7?
You need to return the value, you are just incrementing it and simply not returning it, hence undefined
is added.
const result = Array.from({ length: 7 }, (curr, i) => i + 1 );
console.log(result)
The value return from the function passed to array.from is added to array. Here you are not returning anything so it automatically return undefined
and you get array containing 7 undefined
let abcd= Array.from({length:7},(curr,i)=> {
console.log(curr,i);
return i+1;
})
console.log(abcd); // returns [undefined *7]
A better way for me to create array like this to use spread operator and map()
let abcd = [...Array(7)].map((x, i) => i + 1)
console.log(abcd); // returns [undefined *7]