2

Please I am trying to display the firsts columns of a multidimensional array in JS but when the current item is undefined, the loop ends even when the following items follow the condition of the loop. this is my code.

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

liste_des_points is actually an array built from the rows of a mysql table. N.B: I have tried to display these line independently and it works.

     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

Thanks

4
  • 5
    The loop only goes from 0 to 2. Commented Nov 9, 2017 at 0:33
  • i.e. 3 < 3 === false Commented Nov 9, 2017 at 0:35
  • sorry i meant z<4 Commented Nov 9, 2017 at 5:04
  • Please add console.log(liste_des_points) to the question. Commented Nov 9, 2017 at 16:55

2 Answers 2

1

If liste_des_points[z] is empty, check for liste_des_points[z] as well before calling 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]);
} 
Sign up to request clarification or add additional context in comments.

8 Comments

@Barmar We do not know what liste_des_points[2] is, e.g., delete liste_des_points[2]
He says the array is the results of a query. But I still say, if the element is deleted, alert(liste_des_points[2][0]) would report an error, not alert an empty value.
@Barmar Where does OP state that an empty value is alerted?
He doesn't say that it gets an error when he does that alert.
@Barmar That is true as well. When tried to reproduce the missing code at OP used delete, which led to the Answer. If that is not the case, then OP can omit that portion of the expression.
|
1

Try this:

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

6 Comments

he doesn't want to stop the loop, he's saying that the loop is stopping when it shouldn't.
Oh, I will edit the question to be properly worded. Sorry for that, deleting this.
Well, can't delete now.
Why can't you delete?
After comment, it says vote to delete. Anyways, I edited it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.