3

I'm sure that this is an easy question for JS experts out there. Unfortunately for me I'm not one of them.

I've got the following situation. I'm creating an array in function b that I populate with some new objects. I then return that array back to function a (which called function b).

When I iterate through the returned array, the contents are all undefined. Off the cuff I figure that the JS garbage collector is probably involved here. How would I go about fixing this?

Sincerely,

mj

function a()
{
    var x = b();

    for( var v in x ){
        //print out v.id and v.name
    }
}

function b()
{
    var y = new Array();
    var m = new Object();
    var n = new Object();
    m.id = 1;
    n.id = 2;
    m.name = "alpha";
    n.name = "bravo";

    y.push( m );
    y.push( n );

    return y;
}
Martin
  • 37,119
  • 15
  • 73
  • 82
mj_
  • 6,297
  • 7
  • 40
  • 80

3 Answers3

12

The problem is how you are "iterating" through your array. You are using the for-in statement, and this statement should be used to enumerate object properties, not to iterate over arrays or array-like objects.

From your code:

for( var v in x ){
    //print out v.id and v.name
}

The for-in statement in every iteration will feed v with the name of each property, since you are using an array in your example, v will be '0', '1', etc.

You could access x[v] but I really encourage you to use a sequential for loop, for example:

for (var i = 0; i < x.length; i++) {
  alert(x[i].id);
  alert(x[i].name);
}

There are many reasons why to avoid for-in, when your purpose is "iterate" over numeric indexes on array like objects, see the following questions for more information:

Community
  • 1
  • 1
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
1

You should not interate over an array in that way. You are looping through all of the properties/methods of the array, etc.

You can see this if you alert v http://jsfiddle.net/Xk7yB/

If you use a regular for loop, it works fine:

function a()
{
    var x = b();

    for(var i=0; i<x.length; i++){
         alert(x[i].name);   
    }
}

http://jsfiddle.net/Xk7yB/1/

James Montagne
  • 77,516
  • 14
  • 110
  • 130
1

If you're using jQuery, you can also use:

$.each(x,function(){
    alert(this.id);
    alert(this.name);
});

The jQuery $.each() is most similar to the foreach mechanism you are used to.

arb
  • 7,753
  • 7
  • 31
  • 66