Faarbhurtz
Faarbhurtz

Reputation: 580

Array is undefined in For loop

I get the following error (which doesn't make any sense to me !!):

TypeError: jImages[i] is undefined          

Code:

$.ajax({ url: 'FilterByToestanden.php',
         data: {aantal: $("#aantToestanden option:selected").text(), tekst: $('#bevat').val()},
         type: 'post',
         success: function(data) {
                      var jImages = JSON.parse(data);
                      alert(jImages[0][0]);
                      var filteredImageList = new Array();
                      for (var i=0, len = data.length; i< len; i++)
                      {
                      filteredImageList[i]=jImages[i][0]+jImages[i][1];
                      }
                      alert(filteredImageList);
                  }
});

Upvotes: 1

Views: 97

Answers (2)

ProGM
ProGM

Reputation: 7108

data is a string (JSON string), and jImages is a 2d array. In general data.length (string character number) is different from jImages (number of elements inside the array).

you should do something like:

for (var i=0, len = jImages.length; i< len; i++)

Upvotes: 2

Barmar
Barmar

Reputation: 782785

data.length should be jImages.length.

data.length is the length of the JSON string, which is much more than the length of the jImages array. So you were going beyond the end of the array, resulting in trying to access undefined elements.

Upvotes: 4

Related Questions