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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值