简体   繁体   English

JavaScript中空数组的长度

[英]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 TypeError: Cannot read property 'length' of undefined不是|| 0确切含义。 || 0 part should catch? || 0部分应该抓住?

why doesn't this work? 为什么不起作用? how can i read the length of an array or 0 if there are no entries? 如果没有条目,如何读取数组的长度或0

room.clients is undefined which is why you get that error. room.clients undefined ,这就是为什么您会收到该错误。 The reason it's undefined is because room is a string. undefined的原因是因为room是一个字符串。

A for..in loop iterates over the keys of an object. for..in循环遍历对象的键。 This means that room === "ijxeczyu" , assuming you're passing in your rooms object. 这意味着, room === "ijxeczyu" ,假设你传递你的rooms对象。 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];
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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