0

Hi everyone I just started learning js. One of the assignment is to add all firstname from a list of students to an array. When I tried the following codes

    let students = [
    {
        fname: "Jam",
        lname: "Brazier",
        snum: "0010",

    },
    {
        fname: "Ricardo",
        lname: "Allen",
        snum: "0020",

    }]

and running

    for (let student in students) {
    console.log(student.fname);
}

Got undefined undefined from console. Why is this not working?

I also tried the following

let num_list = [2.99,5,6,3,2,4,5];
for (let num in num_list){
    console.log(num);
}

This time the output is index of each number:

0
1
2
3
4
5
6

How should I fix this code? Thanks a lot for your time.

Null Null
  • 19
  • 5

1 Answers1

0

The type of loop you need is a for... of loop.


Working Example:

let students = [
  {
    fname: "Jam",
    lname: "Brazier",
    snum: "0010",
  },

  {
    fname: "Ricardo",
    lname: "Allen",
    snum: "0020",
  }
]


for (let student of students) {
  console.log(student.fname);
}

Further Reading:

Rounin
  • 27,134
  • 9
  • 83
  • 108