If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Enjoy an ad free experience by logging in. Not a member yet? Register.

Indexing in a javascript array

Now basically there is a tabLinks array (var tabLinks = new Array(). There is a variable called id, which is assigned the value of the href attribute of a link ( we are looping through an array of links and tabLink represents the current link). In the code, there is a line:

Code:

"tabLinks[id] = tabLink;

So id refers to the href attribute value of the link (without a hash) and tabLink is the link itself. tabLinks is the array. My question is are both the attribute and the link itself getting indexed at position 0 of the array, for example? Or is just the link getting indexed? If so, then why have this: [id]? I can't imagine that they are both getting indexed at position 0: [about a]. But if it's just the id getting indexed [about], then why are we assigning the link to this specific index? As you can tell, I'm really confused about how this indexing is working.

Ok, the reason you're confused is because that guy isn't actually using an Array there (at least not a numerically indexed one). The reason his code works is because of the fact that an Array is-an Object in JavaScript, and he's assigning properties to the object, not numerical indexes to an Array.

Now, properties of objects can be set using two operators: the dot operator, or the subscript operator (square brackets). The following are equivalent:

And since all objects in JavaScript can have properties, that is why that guy's code works when he assigns the string ID's to the "array". You'll actually notice that if you take his code, and set tabLinks to be just a Object instead of an Array, the code works just the same.

Try throwing that code into a function and run that function after the page loads. You can also use a tool like Firebug to show you what variables actually store. After the page loads, type this into the Firebug console:

It's not a bad implementation. There really is no "most effective" way to do tabs; just use whatever it takes to get the job done. If you don't feel like including a library like jQuery into your page, then that should work fine. Just test it and make sure that it works on all of the browsers.

However, using a library with a pre-built tabs implementation that has been tried and tested on many different browsers and platforms will probably fair better in the real world.