Home > other >  Why can't I read these properties using """ ${ array[a].name} """
Why can't I read these properties using """ ${ array[a].name} """

Time:07-28

Why can't I read the properties using ${ array[a].name } with For of ? I made an ex with an array of objects just to simplify the problem diagnosis

const movie = [{
    name: "Shrek",
    year: 2001
  },
  {
    name: "Shrek 2",
    year: 2004
  },
  {
    name: "Shrek Third",
    year: 2007
  },
  {
    name: "Shrek For Ever",
    year: 2010
  }
]

forIn = array => {
  for (a in array) {
    console.log(`Index ${a} in Array Object`)
    console.log(`FOR IN array[a] -> ${array[a]}`, array[a])
    console.log(`FOR IN array[a].nome -> ${array[a].nome}`)
    console.log(`FOR IN array[a].year -> ${array[a].year}`)
    console.log('')
  }
}

forOf = array => {
  for (a of array) {
    console.log(`Index of Array -> Object`)
    console.log(a)
    console.log(array[a])
    console.log('')
    /*      console.log(`FOR OF array[a].name -> ${array[a].name}`)  ERROR LINE */
  }
}
forIn(movie)
console.log('')
forOf(movie)

CodePudding user response:

with for of loop a is already the value, it is not the index so use a.name inside the loop

const movies = [  { name: "Shrek", year: 2001 },
        { name: "Shrek 2", year: 2004 },
        { name: "Shrek Third", year: 2007 },
        { name: "Shrek For Ever", year: 2010 }
    ]
   
        for (m of movies) {            
            console.log(m)
            console.log(m.name)
            console.log(m.year)
        }

CodePudding user response:

First iteration 'of' loop:

  • in variable 'a' you have first object from array: { name: 'Shrek', year: 2001 }
  • array[a] is undefined - you cannot access element of array that way
  • you call array[a].name ---> undefined.name ---> error: you cannot access property 'name' of undefined
  • Related