简体   繁体   中英

Length of empty array in javascript

so i'm trying to do one of the most basic things, and i am wondering what's wrong with my approach.

i have an object containing rooms

{ rooms: 
   { ijxeczyu: 
      { Id: 'ijxeczyu',
        teacherName: 'testteacher',
        teacherId: '/#Ikosyfr1NtDcpKbaAAAA',
        clients: [] } },
  getRooms: [Function],
  addRoom: [Function] }

now i want to render their info to a table in jade. for that to work, i want to extract the important stuff and push it to an array

function makeArray(obj) {

  var roomArray = [];

  for (var room in obj) {
    roomArray.push({
      roomId  : room.Id,
      teacher : room.teacherName,
      clients : room.clients.length || 0
    })
  }
  return roomArray;
}

pretty easy. but i can't get that empty clients array to work. TypeError: Cannot read property 'length' of undefined isn't that exactly what the || 0 || 0 part should catch?

why doesn't this work? how can i read the length of an array or 0 if there are no entries?

room.clients is undefined which is why you get that error. The reason it's undefined is because room is a string.

A for..in loop iterates over the keys of an object. This means that room === "ijxeczyu" , assuming you're passing in your rooms object. To get access to the object, you'll have to access the object at that key .

for (var name in obj) {
  var room = obj[name];
  ...
}

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