PositiveGuy
PositiveGuy

Reputation: 47743

Array is lost after passed to a function

I'm getting a length of 0 for the incoming array to this method below and undefined for the array properties that's being passed in below and not sure why:

function BindAlbumDropdownList(aAlbums, defaultAlbumID)
{
    if(aAlbums.length == 0)
        return;

    var albumDropdownID = $("#abumDropdown").attr("id");

    AddDropdownItem("-Select an Album-", "-1", "albumDropdown");

    for(var a in aAlbums)
    {
        alert("a.name, a.id, albumDropdown: " + a.name + "|" + a.id + "|" +  albumDropdownID);
        AddDropdownItem(a.name, a.id, albumDropdownID);
    }
}

I'm passing in an array that was defined earlier in another method that calls this method and the array was defined and passed like this:

var aAlbums = GetAllAlbums(userID, accessToken);
var defaultAlbumID = aAlbums[0].id;

BindAlbumDropdownList(aAlbums, defaultAlbumID)

GetAllAlbums is returning a variable setup like this inside it:

var aFacebookAlbums = []; // array

and returns this array once populated.

but when I enter the for loop in the BindAlbumDropdownList, I'm getting undefined for the array properties as well as the check for length is zero

here's what the alert is giving me:

a.name, a.id, albumDropdown: undefined|undefined|albumDropdown

I am positive GetAllAlbums is returning an array with values in it because
var defaultAlbumID = aAlbum[0].id; gives me a valid value

I noticed that it seems like BindAlbumDropdownList doesn't really know the incoming aAlbums is an array even though I am passing an array to it. Because I'm getting no intellisense showing the property array when trying to do aAlbum.length but I do get the .length property on the array just before I return it from the GetAllAlbums function.

Upvotes: 1

Views: 397

Answers (3)

jason
jason

Reputation: 4801

crap Ive never gotten one before and in my excitement I answered in a comment lol!!

what would you get if you asked for the value of

0.name 1.name 2.name

?

now what would you get if you asked for the value of

a[0].name a[1].name a[2].name

 for(var a in aAlbums)
    {
        alert("aAlbums[a].name, aAlbums[a].id, albumDropdown: " + a.name + "|" + a.id + "|" +  albumDropdownID);
        AddDropdownItem(aAlbums[a].name, aAlbums[a].id, albumDropdownID);
    }

Upvotes: 0

Kyle Nunery
Kyle Nunery

Reputation: 2049

Are you sure you included jQuery ok? Is "abumDropdown" correct for the selector id? You can use for...in with an array in javascript even though it's not recommended.

Upvotes: 0

Reigel Gallarde
Reigel Gallarde

Reputation: 65254

you should use for statement and not for-in statement

for(i=0; i < aAlbums.length; i++)
{
    var a = aAlbums[i];
    alert("a.name, a.id, albumDropdown: " + a.name + "|" + a.id + "|" +  albumDropdownID);
    AddDropdownItem(a.name, a.id, albumDropdownID);
}

Upvotes: 1

Related Questions