zjz的地盘

生命不息,奋斗不止

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.

阅读更多
想对作者说点什么? 我来说一句

javascript技巧

2009年04月10日 8KB 下载

JavaScript方法和技巧大全

2011年04月05日 125KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭