Please am a beginner,can someone please help me out how to use a loop to assign elements to an empty array? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Please am a beginner,can someone please help me out how to use a loop to assign elements to an empty array?

e. g var are=[]; how will I use a loop to put 3 elements in the array

18th Sep 2018, 10:42 PM
tabe Kyrian
tabe Kyrian - avatar
5 Answers
0
To add elements, use .push()
18th Sep 2018, 11:32 PM
James
James - avatar
19th Sep 2018, 10:28 AM
🌴Vincent Berger🌴
🌴Vincent Berger🌴 - avatar
0
thanks but please be more explicit, I tried running the code it didn't work
19th Sep 2018, 10:54 PM
tabe Kyrian
tabe Kyrian - avatar
0
const num = [1,2,3]; var arr = new Array(); let len = num.length; for (let i = 0; i < len; i++) { arr.push(num[i]); } console.log(arr+"\nType of: "+typeof arr+"\nArray true?: "+Array.isArray(arr)); //new Array() is a better way to make new objects/arrays then u use []. The loop loops through the whole object 'num' and check if there is anything present. If there is something present, the loop pushes the founded elements into a new object/array called 'arr'. Since we gave the loop an let i of 0 it will start from the first element of the object/array. i = 0, if the length(i<len) of the num[i] is present push(i++)every element starting from 0(i++) to object arr. Hope this helps👍 https://code.sololearn.com/WcG312lSQ5iF/?ref=app
19th Sep 2018, 11:33 PM
🌴Vincent Berger🌴
🌴Vincent Berger🌴 - avatar
0
✌👍
20th Sep 2018, 2:10 PM
tabe Kyrian
tabe Kyrian - avatar