Fernando López Fernando López - 6 months ago 8
jQuery Question

Iterate two arrays: Cannot read property 'length' of undefined

I want to iterate over two arrays, states and districts, but I get an error-message saying "Cannot read property 'length' of undefined". I don't know what's causing it.

This is my code:

var estados = [ "aguascalientes", "baja-california", "baja-california-sur",
"yucatan", "zacatecas", ];
var municipios = [ [ "aguascalientes", "asientos", "calvillo", "cosio", "tepezala" ],
[ "mexicali", "playas-de-rosarito", "ensenada" ] ];

$("#property_location").change(function () {
$( "#property_location option:selected" ).each(function() {
var i;
var j;
for (i = estados.length - 1; i >= 0; i--) {

if ($( this ).val() == estados[i]) {
console.log(estados[i]);

for (j = municipios[i].length - 1; i >= 0; i--) {
$("#property_municipio option[value='"+municipios[i][j]+"']").show();
}

} else {

for (j = municipios[i].length - 1; i >= 0; i--) {
$("#property_municipio option[value='"+municipios[i][j]+"']").hide();
}
}
}
});
}).change();

Answer

Your problem is that estados has more member than municipios you loop trough every member of estados and check how many member does the municipios sub array have.

for (j = municipios[i].length - 1; i >= 0; i--)

if i is greater than 1 municipios[i] is undefined and you can't calculate the length of undefined. this generate your error.

By the way, you overwrite your loop index i if you use it in both loops. Please use it like that:

for(var i = 0; i < array.length; i++){
   ...
   for(var j = 0; j < array.length; j++){
      ...
   }
}