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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Index of Array 1

Status
Not open for further replies.

greyone

Programmer
Dec 14, 2000
200
CA
I have an array as follows:
var TMonth = new Array('','Jan', 'Feb', 'Mar', 'Apr', 'May','June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');

as we all know TMonth[1] will give us Jan TMonth[2] will give us Feb and so on.
My question is how do i find out the index of the element and display it. For example i want to find the index value of Jan how do i do this. Please help
 
Just wondering why do you have an empty string as element 0?
To find the index of an element you can use:

Array.prototype.getIndex=function(val)
{
var arrlen = this.length;
for(var i=0;i<arrlen;i++)
{
if(this==val){return i}
}
return false
}

x=TMonth.getIndex(&quot;Feb&quot;)

now x is 2 jared@aauser.com
 
Could you explain me the function defination:

Array.prototype.getIndex=function(val)

What is it supposed to mean
 
this way you defined a new method for the array object, this method is getindex and you call it simply with your_array.getIndex(val)
 
A prototype property of an object is very useful. It can be used to achieve inheritance in javascript by puttting another object in the prototype, and also for adding properties and methods to currently existing objects. What the line did above was create a function that any array can use to find the index of a value you pass to the function.

so if you had another array called TDays you could find the index of &quot;Mon&quot; like this:

TDays.getIndex(&quot;Mon&quot;)

If the function returns false, it means it could not find the value. Notice the use of the keyword 'this' above. 'this' can be used because I added the function to the Array's prototype property and the function knows the current object is the array that called it. jared@aauser.com
 
hey i just tried the code but it is returning false everytime. I wonder what the problem is
 
TGML from this board screwed up the code:

Just wondering why do you have an empty string as element 0?
To find the index of an element you can use:

Array.prototype.getIndex=function(val)
{
var arrlen = this.length;
for(var i=0;i<arrlen;i++)
{
if(this==val){return i}
}
return false
}

x=TMonth.getIndex(&quot;Feb&quot;)

now x is 2

jared@aauser.com
 
Just one more question is there a FAQ to understand in more detail what you explained me abourt the array.prototype
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top