Link to home
Start Free TrialLog in
Avatar of sstolp2005
sstolp2005

asked on

Need help with javascript array

Hi all.  Thank you in advance.

First I create an array like this:

var myArray = [];

I have some objects that are keeping track of information for me.  I have created them as thus:

var x = {a: "someinfo", b: "some more info" myID: "ID0"}

Then I add it to an Array like this:

myArray.push(x);

I set x to null, and will use it again in the future to possibly add more objects to the array. All of my objects have the exact same structure, but of course have a different "myID"

This "seems" to work fine for me except when it comes time to pull the information for one of the objects out of the array. I try to get the index as follows:

var myX = searchArray(myArray, "ID0");

and my searchArray function looks like this:

searchArray : function(arr, toFind)
{
  if(arr.constructor != Array)
    {
    return -1;
    }
    for(var i = 0, len = arr.length; i < len; i++)
    {
      if(arr[i].myID == toFind)
      {
        return i;
      }
    }
return -2;
}

I thought this would loop through the array until it found a matching myID and then send that index back to me so I could use the index to pull the object from the array.  When I have multiple objects in the array, and I write out whet the myID "should" be, it always comes back as 'undefined'.  I don't understand this at all.  There are clearly as many objects in the array as I have added, and on another function, it will actually loop through and write the myID.

I am so confused, and not very good with javascript (obviously).

This shouldn't be this difficult.  Can anyone help?

Thank you.

Steve
ASKER CERTIFIED SOLUTION
Avatar of HonorGod
HonorGod
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sstolp2005
sstolp2005

ASKER

Wow.  This really helped.  I think I can figure it out from here.  Thank you SO much!!
You are very welcome.  Thank you for the grade & points.

Good luck & have a great day.