for loop - JavaScript 'for in' statement giving unpredicted results - Stack Overflow

I have the following code:var images = document.getElementsByTagName('img');if (screen.width

I have the following code:

var images = document.getElementsByTagName('img');

if (screen.width > 640) {
    for (var image in images) {
        image = images[image];

        console.log(image['src']);
    }
}

There is only one image on the page, but for some reason the for ... in statement is looping through images three times. Why is this?

Example: /

I have the following code:

var images = document.getElementsByTagName('img');

if (screen.width > 640) {
    for (var image in images) {
        image = images[image];

        console.log(image['src']);
    }
}

There is only one image on the page, but for some reason the for ... in statement is looping through images three times. Why is this?

Example: http://jsfiddle/OliverJAsh/C8egs/

Share Improve this question asked Jan 11, 2012 at 12:21 user1082754user1082754 3
  • How does this snippet of code get invoked? – J. Holmes Commented Jan 11, 2012 at 12:23
  • For the purpose of this example, it is inline JavaScript on the HTML page. – user1082754 Commented Jan 11, 2012 at 12:24
  • Have you tried replacing the image variable used in the assignment with another name, I'm wondering if a conflict of the name could be occurring? I.E. you are using the var image in the for in, but then re-assign it, maybe try another variable? – onaclov2000 Commented Jan 11, 2012 at 12:28
Add a ment  | 

5 Answers 5

Reset to default 6

You're not just looping through the list of elements, but also the named methods:

  • length
  • item
  • namedItem

The correct approach is:

for (var i=0; i<images.length; i++) {
    var image = images[i];

    console.log(image['src']);
}

Instead of using document.getElementsByTagName('img'), you can also use document.images.

http://jsfiddle/C8egs/2/

The trouble is with your for..in loop. A for..in loop loops through all the enumerable properties of an object. getElementsByTagName returns a NodeList. All nodeList objects have at least two additional properties besides the elements found: a length property, containing the number of elements found, and an item property, a method (following the DOM specification) to access elements numerically.

If you are looping through an array-like object, you should use a plain for loop instead:

for (var i = 0; i < images.length; i++) {
    console.log(images[i].src);
}

for(var x in var) shouldn't be used for going through an array as it goes through the keys in the object.

If you do:

for (var image in images) {
        console.log(image );
}

You'll notice that the console output will show 'length' (as well as any other properties on the object);

Instead use it like:

for (var i=0; i < images.length; i++) {
    var image = images[i];

    console.log(image['src']);
}

The looping is not three times actually it is looping four times. The looping differs in different browsers. I checked it in IE8 and FireFox In fireFox it looped for four times and the console output is

  • image node
  • length
  • item
  • namedItem

In IE8 it looped twice

  • length
  • index position of the img tag

So you have to correct your for loop as shown below

var images = document.getElementsByTagName('img');
if (screen.width > 640) {
    for (var i in images) {
        image2 = images[i];
        if(image2.nodeName == "IMG" || image2.nodeName == "img")
        console.log(image2['src']);
    }
}

javascript's for in iterates the proprty of an object, not the content of the array. try this:

var obj = {"name": "one", "date": 10, "help": false};

for (var key in obj) {
    alert(key);
} 

you have to resort for iteration by accessing the index of the item in the array.

for (var idx = 0, numImages = images.length; idx < numImages ; idx++) {
      image = images[idx];
      console.log(image['src']);      
} 

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745426656a4627209.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信