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;
}
The problem is how you are “iterating” through your array. You are using the
for-instatement, and this statement should be used to enumerate object properties, not to iterate over arrays or array-like objects.From your code:
The
for-instatement in every iteration will feedvwith the name of each property, since you are using an array in your example,vwill be'0','1', etc.You could access
x[v]but I really encourage you to use a sequentialforloop, for example: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: