JavaScript的五個技巧

五條javascript技巧幫助你提高代碼質量:
 1.只在<form>元素上使用submit事件
  綁定事件處理表單時,使用表單得submit事件而不是click事件。
 2.如果可點擊,確認是否是鏈接

 3.簡單的for循環優化
  下面是對for循環做的一個非常簡單的改變,但是它確可以提高循環的效率

 

 for ( var i = 0; i < elements.length; ++i )
 
for ( var i = 0, j = elements.length; i < j; ++i )


   第二行代碼中elements.length被存在變量j中,所以不必在每次循環的時

候重複讀取它。

 
 4.事件處理時使用匿名函數(Use anonymous functions for event handlers)
  象下面這樣比較短的函數使用匿名函數比引用一個其他地方命名的函數可

讀性要高
  

anchor.onclick = function() {
                    map.goToPosition( home );
                    
return false;
                 }


 5.使用Array.join代替字符串連接(concatenating strings)

  遇到比較長的字符串連接的時使用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(' ');

 注:關於最後一條好像還有爭議

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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章