简体   繁体   中英

Why am I getting Cannot read property 'startsWith' of undefined in this for loop?

I am trying to sort an array by 'version' and then identify all string that begin with 'iPad'.

The following code does not log anything and returns an error.

orderedUsers: function () {
  let newarray = sortBy(this.jobs, 'version').reverse()
  for (let i in newarray) {
    if (i.version.startsWith('iPad')) {
      console.log(i.version);
    }
  }
  return newarray

error:

TypeError: Cannot read property 'startsWith' of undefined

If I remove the for-loop and just put:

orderedUsers: function () {
  let newarray = sortBy(this.jobs, 'version').reverse()
  return newarray

The list is correctly sorted by version. This makes me think the error is related to how I have written my for-loop or if statement.

What am I doing wrong here.

The for...in construct is not doing what you think here. It is is designed to iterate over objects. So in this case it is treating newArray as an object but with the property names as the array indices. Arrays in Javascript are just objects with numeric property names. More specifically if you changed your code to:

for (let i in newarray) {
    if (i.version.startsWith('iPad')) {
      console.log(i);
    }
  }

You would clearly see the problem. i is a number and not a job object.

fix:

orderedUsers: function () {
  let newarray = sortBy(this.jobs, 'version').reverse()
  for (let i in newarray) {
    if (newarray[i].version.startsWith('iPad')) {
      console.log(newarray[i].version);
    }
  }
  return newarray

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM