+ 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
5 Answers
0
To add elements, use .push()
0
thanks but please be more explicit, I tried running the code it didn't work
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
0
āš