![]() |
Indexing in a javascript array
Hey all,
I read this tutorial about creating javascript tabs: http://www.elated.com/articles/javascript-tabs/ 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;Thanks for any response. |
id doesn't refer to an attribute, it is a integer that tells the program where in the array to store tabLink.
Code:
id=0;["test", "foo"]the id value tells it were to store "tabLink" in the array |
I'm not sure how this assigns an integer to id:
Code:
var id = getHash(tabLink.getAttribute('href')); |
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: Code:
var myObj = new Object();Code:
var myArr = new Array(); Code:
var tabLinks = new Object(); |
So what ends up happening with this guy's code is that tabLinks becomes an Object with 3 properties: "about", "advantages", and "usage". They can be referred to using both dot and subscript operators:
Code:
alert( tabLinks.about );Code:
console.dir( tabLinks ); |
Thanks do you think this is the most effective way to create tabs like this in pure javascript (not including jQuery)?
|
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. -Greg |
| All times are GMT +1. The time now is 02:59 PM. |
Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.