collection item() vs array []

倖福魔咒の 提交于 2019-12-22 13:53:13

问题


Apologies if this is a duplicate - it is not easy to search for.

I have today come across TWO questions using someArrayOrCollection.item(i) instead of my preferred someArrayOrCollection[i]

Example: parse XML attribute value using javascript

var sTitle1 = item.getElementsByTagName("title").item(0)....

where I would use

var sTitle1 = item.getElementsByTagName("title")[0]....

Last time I saw these where when only IE supported that notation.

My first instinct when I see .item() is to correct it to []. Should I or is it harmless or perhaps even best practice these days?

Interestingly almost all the collections at MDN mentions the item method but their examples use [] - for example https://developer.mozilla.org/en-US/docs/Web/API/NodeList


回答1:


For NamedNodeMaps [] acts as a sugar for both .item and .getNamedItem, which makes it possible to build a contrived example where index will be different from .item:

<div id="x" 2e0="wtf" class="foo" ></div>

<script>
a = document.getElementById("x").attributes;
console.log(a["2e0"].nodeValue)         // wtf
console.log(a.item("2e0").nodeValue)    // foo
</script>

Needless to say, this is purely theoretical, in the real life [] is a safe choice.



来源:https://stackoverflow.com/questions/16684022/collection-item-vs-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!