当数组的项未定义时,javascript结束循环

时间:2017-11-09 00:31:00

标签: javascript

请问我正在尝试在JS中显示多维数组的第一列,但是当当前项未定义时,即使以下项跟随循环的条件,循环也会结束。这是我的代码。

for(var z = 0; z < 4; z++) {
     if(typeof(liste_des_points[z][0])!='undefined')
     alert(liste_des_points[z][0]);
 } 

liste_des_points实际上是一个从mysql表的行构建的数组。 N.B:我试图独立显示这些线并且它有效。

     alert(liste_des_points[0][0]);//this line display 0
     alert(liste_des_points[1][0]);//this line display 1
     alert(liste_des_points[2][0]);/*display anything because the value is      absent in the database*/
     alert(liste_des_points[3][0]);//this line display 3

由于

2 个答案:

答案 0 :(得分:1)

试试这个:

for(var z = 0; z <= 3; z++) {
     if(typeof(liste_des_points[z][0]) !== 'undefined') {
         alert(liste_des_points[z][0]);
     }
 } 

答案 1 :(得分:1)

如果liste_des_points[z]为空,请在致电liste_des_points[z]之前检查typeof()

for(var z = 0; z < 4; z++) {
  if(liste_des_points[z] && typeof(liste_des_points[z][0])!='undefined')
  alert(liste_des_points[z][0]);
}