javascript開發幾條技巧與效能最佳化總結

來源:互聯網
上載者:User

技巧一之setTimeout.

應用案例:比如你想一個函數迴圈執行10次,怎麼辦?以前通常是先setInterval,然後clearInterval,技巧一就是克服這個問題

 代碼如下 複製代碼
(function () {
    var i = 0;
    function job() {
        console.log(i++);
        if (i < 10) {
            setTimeout(job, 1000);
        }
    }
    job();
 
})();

上面這個job函數就只會乖乖的執行10次.然後自動停止

 

技巧二之高效的for迴圈

應用案例:拋棄傳統的迴圈方式

 代碼如下 複製代碼
(function () {
   var arr=[];
   for(var i=arr.length;i--;){
      doStuff();
   }
})();

這個方式為什麼高效?

一:少了一個參數l=arr.length;

二:for語句中間那個玩意少進行了一次計算,以前的話是for(i=0;i<l;i++)這樣的話中間的語句會先比較i<l  然後比較出來的結果在

跟true 或者false比較,自然多了次計算 

技巧三之高效賦值

應用案例:拋棄傳統的if判斷賦值

 代碼如下 複製代碼
var i=1,ret;
  ret=i!==1||true;
  console.log(ret);

以上代碼會很神奇的告訴你ret會是true.高效吧不用if(i!==1)了在賦值了

 

技巧四之強悍的簡短的attr

應用案例:setAttribute,getAttribute.這個方法不僅可以設定標準的屬性,還可以設定任意屬性,相容好

 代碼如下 複製代碼
function attr(elem, name, value) {
    var ret;
    if (value) {
        if (/msie [6-7].0/i.test(navigator.userAgent)) {
            ret = elem.getAttributeNode(name);
            if (!ret) {   //ie6 7不合法的屬性設定捕鳥,通過這裡可以設定
                ret = document.createAttribute(name);
                elem.setAttributeNode(ret);
            }
            ret.nodeValue = value + "";
        } else {
            elem.setAttribute(name, value);
        }
        return elem;
    } else {  //ie6 7有得屬性擷取不鳥
        ret = elem.getAttribute(name);
        fixIe = elem.getAttributeNode(name).nodeValue;
        ret = ret ? ret : fixIe ? fixIe : undefined;
        return ret;
    }
}


以上方法如何測試呢?

 代碼如下 複製代碼

attr(document.getElementById(“test”), “classxx”, “xx”);
alert(attr(document.getElementById(“test”),”classxx”)); 

技巧五之getElementsByClassName.

應用案例 :以前js沒什麼架構的時候,大家都再模仿這個方法,看看今天我是怎麼高效的模仿出它來.這也不愧是js初學者的經典代碼

 代碼如下 複製代碼

(function () {
   var getElementsByClassName=function(cls,context){
      var root = context || document;
    return document.querySelectorAll ? root.querySelectorAll("." + cls) : root.getElementsByClassName ?
           root.getElementsByClassName(cls) : help("*", cls, context);
   }
   var help=function(tagName,cls,context){
        var root= context || document,
            ret=[],elems,i,
            rcls=new RegExp("^|\s+"+cls+"\s+|$");
        elems = c.getElementsByTagName(tagName || "*");
        for(i=elems.length;i--;){
            if(rcls.test(elem[i].className)){
              ret.push(elems[i]);
            }
        }
        return ret;
   }
})();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.