tags:

views:

78

answers:

4

Hello everybody.

I have a question. I was recently writing some javascript code in dreamweaver and in it's code complete everytime i would deal with array of elements it will give me array.item(n) rather then array[n]

What is the difference between those two ?

Some example code:

function hideAllSubMenu(){
    var submenu = document.getElementsByTagName("div");
    for(var i = 0; i < submenu.length; i++)
    {
     if(submenu.item(i).className == "submenu_wrap")
      submenu.item(i).style.display = "none";
    }
}

However it can be writen in such maner as well

function hideAllSubMenu(){
    var submenu = document.getElementsByTagName("div");
    for(var i = 0; i < submenu.length; i++)
    {
     if(submenu.[i].className == "submenu_wrap")
      submenu.[i].style.display = "none";
    }
}

It is somewhat confusing for somebody like me who in his first steps on learning core javascript. Can somebody explain to me what is a difference

+1  A: 

i think you meant submenu[i] in the second example and item(n) and [n] are synonymous

Scott Evernden
I just want to know what is the difference (if any) between array.item(n) and array[n]I never saw any JavaScript example using array.item(n) however firebug apparently has no problem compiling it.
Dmitris
'synonymous' === 'no difference'
Scott Evernden
A: 

They both do the same thing. Arrays in JavaScript are pretty flexible. For example you can define an array and start treating it as a hash.

a = []
a[0] = "value1"
a["key1"] = "value2"

If you're just getting into JavaScript development I would definitely recommend Firebug for Firefox. This will allow you to easily debug your code, log errors and messages and even execute JavaScript from a console after your page has loaded.

Andrew Dwyer
+4  A: 

The item method is available on some node lists of the DOM.
The [] is array accessor.

So you can use item when manipulating with DOM. But not on a normal array.
Generally I would suggest to always use [] as it is just works in all cases.

Dmytrii Nagirniak
Thanks for the answer, that's what i wanted to know.
Dmitris
+1  A: 

First of all, there isn't anything built-in such as Array.item in Javascript.

document.getElementsByTagName returns a nodelist object which looks and behaves like an array, but it isn't an Array. However, nodelist[i] and nodelist.item(i) are equivalent.

Chetan Sastry
I never claimed there is something like that build in JavaScript.Thats why i gave example to clarify about my question.Thanks for the answer.
Dmitris
I was just clarifying that you can't use Array.item() in regular arrays.
Chetan Sastry