How to push elements into array in JavaScript

2 Answers

0 votes
const arr = [];
for (let i = 0; i < 5; i++) {
    arr.push(() => i);
}

m = arr.map(x => x()); 

console.log(m);




/*
run:
 
[ 0, 1, 2, 3, 4 ]
    
*/

 



answered Mar 16, 2020 by avibootz
0 votes
const arr = [];
for (const i of [0, 1, 2, 3, 4]) {
    arr.push(() => i);
}

m = arr.map(x => x()); 

console.log(m);




/*
run:
 
[ 0, 1, 2, 3, 4 ]
    
*/

 



answered Mar 16, 2020 by avibootz

Related questions

1 answer 164 views
1 answer 174 views
1 answer 134 views
2 answers 149 views
1 answer 110 views
2 answers 255 views
...