JavaScript for…in vs for

前端 未结 22 1429
悲哀的现实
悲哀的现实 2020-11-22 07:15

Do you think there is a big difference in for...in and for loops? What kind of \"for\" do you prefer to use and why?

Let\'s say we have an array of associative array

22条回答
  •  温柔的废话
    2020-11-22 07:32

    Watch out!

    If you have several script tags and your're searching an information in tag attributes for example, you have to use .length property with a for loop because it isn't a simple array but an HTMLCollection object.

    https://developer.mozilla.org/en/DOM/HTMLCollection

    If you use the foreach statement for(var i in yourList) it will return proterties and methods of the HTMLCollection in most browsers!

    var scriptTags = document.getElementsByTagName("script");
    
    for(var i = 0; i < scriptTags.length; i++)
    alert(i); // Will print all your elements index (you can get src attribute value using scriptTags[i].attributes[0].value)
    
    for(var i in scriptTags)
    alert(i); // Will print "length", "item" and "namedItem" in addition to your elements!
    

    Even if getElementsByTagName should return a NodeList, most browser are returning an HTMLCollection: https://developer.mozilla.org/en/DOM/document.getElementsByTagName

提交回复
热议问题