js基礎(chǔ):JavaScript的五個(gè)技巧
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
五條javascript技巧幫助你提高代碼質(zhì)量: 1.只在<form>元素上使用submit事件 綁定事件處理表單時(shí),使用表單得submit事件而不是click事件。 2.如果可點(diǎn)擊,確認(rèn)是否是鏈接 3.簡單的for循環(huán)優(yōu)化 下面是對(duì)for循環(huán)做的一個(gè)非常簡單的改變,但是它確可以提高循環(huán)的效率 for ( var i = 0; i < elements.length; ++i ) for ( var i = 0, j = elements.length; i < j; ++i ) 第二行代碼中elements.length被存在變量j中,所以不必在每次循環(huán)的時(shí)候重復(fù)讀取它。 4.事件處理時(shí)使用匿名函數(shù)(Use anonymous functions for event handlers) 象下面這樣比較短的函數(shù)使用匿名函數(shù)比引用一個(gè)其他地方命名的函數(shù)可讀性要高 anchor.onclick = function() { map.goToPosition( home ); return false; } 5.使用Array.join代替字符串連接(concatenating strings) 遇到比較長的字符串連接的時(shí)使用Array.join代替字符串連接可以獲得更好的效率而且可讀性更高。 var text = 'There are' + elements.length + 'members in the elements array.'; var text = ['There are', elements.length, 'members in the elements array.'].join(' '); 注:關(guān)于最后一條好像還有爭議 On 12 Sep 07 Stuart Colville said: I'd disagree with the last item on using Array.join for concatenating strings: Firstly, the only real benefit in using this approach is when you are concatenating a lot of strings together. With three strings it may also actually be slower due to the overhead of initialising the array. Secondly the performance increase from using Array.join in the right situation is generally only seen in IE due to it's slow JavaScript engine which has not seen the same levels of optimisations that have been made in other browsers. Update A number of people have mentioned to me that the Array.join technique for string concatenation is a bad one, particularly if you're only doing it with a small number of strings. Our benchmarks show it being faster for IE when you get to about 6/7 string concatenations, so it's been useful to us in some situations. But I'd agree with Stuart below that for the average situation it's not going to be worth it. However, I don't see using Array.join() for string concatenation as an abuse of JavaScript.
該文章在 2010/8/18 10:21:51 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |