Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

getIndex function

Status
Not open for further replies.

duponty

Instructor
Oct 25, 2000
101
CA
Hi,
I am looking for a function that would give me the index of a specified object in a array.

eg:

toto = new array()
toto["object1"] = image.gif

I want the index of "object1"

thanks
 
This function takes the member who's index you want, and the array it belongs to. If -1 is returned, then there is no matching element. Also, it will match integers. You could probably extend it to match anything actually - even objects?


function getIndex(member,array){
var index = -1;
for(var j=0;j<array.length;j++){
if(array[j] == member){
index = j;
break;
}
}
return index;
}


e.g. for the array:

var people = new Array(&quot;Ben&quot;,&quot;Gus&quot;,&quot;Tim&quot;,4,&quot;Coopth&quot;);

the call: getIndex(&quot;Tim&quot;,people) returns 2
and getIndex(4,people) returns 3

Hope this works for you.
b2 - benbiddington@surf4nix.com
 
there's a problem in what you're trying to do... once you use an associative array, you can't use it ordinally again..

so, you could use bangers suggestion if you had something like:

var x = new Array();
x[0] = &quot;image.gif&quot;;

but, using your example

var x = new Array();
x[&quot;bob&quot;] = &quot;image.gif&quot;;

you won't be able to access that with an index other than &quot;bob&quot;

you could get that by using a for in loop however.

function getIndex(m, a)
{
for(var i in a)
{
if(a == m)
{
return i;
}
}
return -1;
}

this should work for associative and ordinal arrays...

although it would be nicer to prototype it to the Array Object.

Array.prototype.indexOf = function(m)
{
for(var i in a)
{
if(this == m)
{
return i;
}
}
return -1;
}

so now you can call it like so:

var x = new Array();
x[&quot;bob&quot;] = &quot;image.gif&quot;;
var y = x.indexOf(&quot;image.gif&quot;); luciddream@subdimension.com
 
make that:
function getIndex(m, a)
{
for(var i in a)
{
if(a == m)
{
return i;
}
}
return -1;
}


and:

Array.prototype.indexOf = function(m)
{
for(var i in a)
{
if(this == m)
{
return i;
}
}
return -1;
}
luciddream@subdimension.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top