Why do nodelists contain extra undefined items that are not reflected in its length property?

别说谁变了你拦得住时间么 提交于 2019-12-01 11:00:05

The two additional properties that the for in iteration statement catches are:

  • length
  • item

Let me give you a simple example. Let's say that there are 3 SPAN elements on the page.

var spans = document.getElementsByTagName( 'span' );

Now, spans is a NodeList object which contains 5 properties:

  • 0
  • 1
  • 2
  • length
  • item

The first 3 properties are indexes and they contain references to those SPAN elements. The other two properties - length and item - are two additional properties. All NodeList objects have these two properties.

The for in statement iterates over all 5 properties of the NodeList object, which is probably not what you want. Therefore, use a regular for statement.

var i, span;

for ( i = 0; i < spans.length; i++ ) {
    span = spans[i];
    // do stuff with span
}

for-in iterates through the all enumerable properties of the object such as length and item (this is your situation). This is where two more results come from. It will also enumerate everything added to object prototype.

for loops through the numeric indeces and doesn't take into consideration enumerable properties. That is why it much more reliable to use former way.

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