关闭

JavaScript的五个技巧

339人阅读 评论(0) 收藏 举报

五条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.

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:55118次
    • 积分:996
    • 等级:
    • 排名:千里之外
    • 原创:35篇
    • 转载:24篇
    • 译文:3篇
    • 评论:17条
    文章分类