Skip to content

Looping through JavaScript arrays

Wed 11th April 2012

I’ve just spent over an hour and a half (plus however long I spent last night before my battery ran out at 2am) hunting for a bug in my current JavaScript project, and it turned out that I was expecting to be able to do something I regularly do in other languages (PHP, and even Java!), but cannot in JavaScript.

var choices = [obj1, null];
var l = [];
var biggest = 0;
for(c in choices)
{
    if(choices[c] === null)
    {
        l[c] = 0;
    }
    else
    {
        l[c] = calculateLength(choices[c]);
    }
    biggest = Math.max(l[c], biggest);
}
console.log("biggest = "+biggest);

This code was part of a work in progress, so it seemed to be working, but I was obviously expecting a few kinks to iron out. When the code was occasionally printing out biggest = undefined, I was a bit confused, but half expectant of something being wrong. As I dug deeper, and stuck in mountains of console.log() debug statements, I became more perplexed.
I just couldn’t work it out; all along the way the correct values were being returned. I could even console.log(l); and get what I expected.
Eventually it dawned on me that if I print the whole array on one line and it is fine, then view an element of that array on the next line and it is undefined, I must be doing something wrong with the array access.

After reading this blog post on mastering JavaScript arrays, I realised that the foreach syntax in JavaScript must be doing something a big odd, and not actually giving me the intended effect of looping through values of 0 to 1 in the variable c.

var choices = [obj1, null];
var l = [];
var biggest = 0;
for(var c=0; c<choices.length; c++)
{
    if(choices[c] === null)
    {
        l[c] = 0;
    }
    else
    {
        l[c] = calculateLength(choices[c]);
    }
    biggest = Math.max(l[c], biggest);
}
console.log("biggest = "+biggest);

Adjusting my for loop to be a conventional counting one seems to have done the trick. The lesson is that JavaScript does not support foreach for arrays, which is a shame. Maybe it’s on the way in ECMAScript 5?

Advertisements

From → Programming

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: