zoukankan      html  css  js  c++  java
  • JavaScript Patterns 2.3 For loops

    HTMLCollections are objects returned by DOM methods such as:

    • document.getElementsByName()

    • document.getElementsByClassName()

    • document.getElementsByTagName()

       

    HTMLCollections, which were introduced before the DOM standard and are still in use today

    document.images

    All IMG elements on the page

    document.links

    All A elements

    document.forms

    All forms

    document.forms[0].elements

    All fields in the first form on the page

       

    // used i+=1 instead of i++ to follow the rule of JSLint

    for (var i = 0, max = myarray.length; i < max; i += 1) {
    
        // do something with myarray[i]
    
    }  

    • Use one less variable (no max)

    • Count down to 0, which is usually faster because it's more efficient to compare to 0 than to the length of the array or to anything other than 0

    The first modified pattern is:

    var i, myarray = [];
    
    for (i = myarray.length; i--;) {
    
        // do something with myarray[i]
    
    } 

    And the second uses a whileloop:

    var myarray = [],
    i = myarray.length;
    
    while (i--) {
    
        // do something with myarray[i]
    
    } 
  • 相关阅读:
    网站数据库
    提笔不知道说啥
    预祝大家新年快乐
    又..
    明日出发
    吸气呼气
    网吧
    光阴似箭
    <转>生活中的各种食品安全问题
    老了吗?
  • 原文地址:https://www.cnblogs.com/haokaibo/p/for-loops.html
Copyright © 2011-2022 走看看