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 282 views
1 answer 279 views
1 answer 224 views
2 answers 277 views
1 answer 197 views
2 answers 378 views
...