未捕获的TypeError:无法读取未定义的属性'xxxx',但已定义

时间:2016-05-28 10:02:53

标签: javascript jquery

几小时前我遇到了这个问题。 我在我的Jquery函数中编写了这些函数来检查Value in Variable是否存在。

console.log("in tr");
console.log(tmpRoomlistArray[c].room_name);
let roomName = tmpRoomlistArray[c].room_name;

当我跑步并查看Google Chrome控制台时。它显示了这样的结果。

Rome  <<< In console.log It shows valid value                                   
in tr                                                       
Uncaught TypeError: Cannot read property 'room_name' of undefined << 
This is what happen when I assign in to a variable and this is what I need 

会发生什么事?我现在瞎了..

编辑:编辑问题内容

3 个答案:

答案 0 :(得分:1)

我已经解决了。这只是一个我忽略的愚蠢问题。关于数组索引。

我只是把

tmpRoomlistArray[c-1]

进入我的功能并且有效。我认为解决方案只是休息更多,所以你可以更清楚地看到问题。

对于那些想知道发生了什么的人,请在下面阅读。

我有一个在表中插入行的函数,这个函数有2个参数,就是一个数组。所以这个函数会将行连续插入表中。它不会停止直到它到达阵列的末尾。

var day = ["1","2","3"];
var room = ["room1","room2","room3",....,"room16"] // 16 Elements;
var timeForHeader = ["08:00","09:00",....."20:00"] // 25 Elements; 

function addRow(paramDay,paramRoom){ 
 // this function will create many rows depends on paramRoom length and columns depends on length of time header.
   var dayLength = day.length;
   var roomLength = room.length;
   var timeForHeaderLength = timeForHeader.length;
   for(var i = 0; i < dayLength; i++)
   {
      // this is for rows
       for(var c = 0; c < timeForHeaderLength+1; c++)
       {
          // I made c +1 timeForHeaderLength because I want a header 
          //this is for column
          if(c == 0)
          { 
            // if c == 0 mean I will insert a header row element in my table
             var tr = $("<tr/>");
             var td = $("<td/>",{text:timeForHeader[0]+" - "+timeForHeader[1]}).appendTo(tr);
             ...
             ...
             var td23 = $("<td/>",{text:timeForHeader[23]+" - "+timeForHeader[24]}).appendTo(tr);
             $("#mytableId").append(tr);
          }else{
            // this row that contain room's name and content
            // and this is the part that cause me a problem.
            // in this else condition c must be 1-17 so when I access to tmpRoomlistArray that contains 16 Element
            // So right now You guys should know right. The tmpRoomlistArray's index must be 0 - 16


            // it worked when c is between 1 - 16, But it didn't work on the last c cause c is equal to 17
             console.log(tmpRoomlistArray[c].room_name);
            let roomName = tmpRoomlistArray[c].room_name;
            //It should be 
            let roomName = tmpRoomlistArray[c-1].room_name;
            // Hahahahahahahahahahahahahahahahahhaha
          }              
       }

   }
}

答案 1 :(得分:0)

tmpRoomlistArray [c]未定义。

尝试打印:

  console.log(tmpRoomlistArray[c]);

 console.log(tmpRoomlistArray);

而不是

console.log(tmpRoomlistArray[c].room_name);

您也可以使用

  debugger 

在javascript代码中观察数组的值。

答案 2 :(得分:0)

使用var而不是let?

可以让我们寻找更强类型的东西吗?