MillerMedia
MillerMedia

Reputation: 3671

Cannot read property 'length' of undefined in For loop (jQuery)

I'm having a weird problem with part of my code and a 'for' loop. Here's the snippet of code that is strange:

var length_value = entry_array.length;

console.log(length_value);

for(var k = 0; k <= length_value; k++){
    j = k + 1;
    $.each(entry_array[k], function(key, value){
        post_data = post_data + key + j + '=' + value + '&';
    }); 
}

When I run the code it logs 3 to the console (which is the number of elements in the entry_array array variable. When it goes to run the for loop, it gives me a Cannot read property 'length' of undefined. I've run the for loop successfully by swapping out length_value for 3 and it works. I've tried this:

length_value = entry_array.length; //Thinking it had something to do with 'scope'

And this:

var length_value = parseInt(entry_array.length) //Thinking it had something to do with the variable type

And neither worked. So the for loop syntax is correct and entry_array.length has a value but it doesn't work together. What's going on here? Thanks for your help!

Upvotes: 0

Views: 3985

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93631

0-based arrays should be indexed from 0 to < length, not <= length

var length_value = entry_array.length;

console.log(length_value);

for(var k = 0; k < length_value; k++){
    j = k + 1;
    $.each(entry_array[k], function(key, value){
        post_data = post_data + key + j + '=' + value + '&';
    }); 
}

e.g. If you have 3 elements, you want indexes of 0, 1 & 2. <= will give 0, 1, 2 & 3

If there are further issues, you need to show a sample of the array content

Upvotes: 3

Related Questions