Home > Net >  how to create new array using push method on javascript
how to create new array using push method on javascript

Time:12-15

Im trying to create new array similar to myCourses array using push method.

But somewhat it keeps log only one string at a time instead of creating a new similar array like myCourses array:

let myCourses = ["Learn CSS Animations", "UI Design Fundamentals", "Intro to Clean Code"]
for (let i = 0; i < myCourses.length; i  ) {
    let a = []
    a.push( a  = myCourses[i] )
    console.log(a) 
}

CodePudding user response:

Due to my comment above, the correct solution (if we accepted creating new array this way, using for loop) is

let myCourses = ["Learn CSS Animations", "UI Design Fundamentals", "Intro to Clean Code"]

// declare a only once
let a = []
for (let i = 0; i < myCourses.length; i  ) {
    // a  = myCourses[i] is non-sense in this case
    a.push( myCourses[i] )
}

console.log(a);
// write into console the result, just once, not in every loop 
// returns ["Learn CSS Animations", "UI Design Fundamentals", "Intro to Clean Code"]

  • Related