编程小贴士

给你的编程提供小点子


20个超实用的JavaScript技巧及最佳实践

 众所周知,JavaScript是一门非常流行的编程语言,开发者用它不仅可以开发出炫丽的Web程序,还可以用它来开发一些移动应用程序(如PhoneGap或Appcelerator),它还有一些服务端实现,比如NodeJS、Wakanda以及其它实现。此外,许多开发者都会把JavaScript选为入门语言,使用它来做一些弹出窗口等小东西。

 
       在这篇文章中,作者将会向大家分享JavaScript开发的小技巧、最佳实践等非常实用的内容,不管你是前端开发者还是服务端开发者,都应该来看看这些小技巧,它们绝对会让你受益的。
 
        文中所提供的代码片段都已经过最新版的Chrome 30测试,该浏览器使用V8 JavaScript引擎(V8 3.20.17.15)。
 
1.第一次给变量赋值时,别忘记var关键字
给一个未声明的变量赋值,该变量会被自动创建为全局变量,在JS开发中,应该避免使用全局变量。
 
2.使用===替换==
并且永远不要使用=或!=。
 
[js] view plaincopy
[10] === 10    // is false  
[10]  == 10    // is true  
’10’ == 10     // is true  
’10’ === 10    // is false  
 []   == 0     // is true  
 [] ===  0     // is false  
 ” == false   // is true but true == “a” is false  
 ” ===   false // is false   
 
3.使用分号来作为行终止字符
       在行终止的地方使用分号是一个很好的习惯,即使开发人员忘记加分号,编译器也不会有任何提示,因为在大多数情况下,JavaScript解析器会自动加上。 
 
4.创建构造函数
[js] view plaincopy
function Person(firstName, lastName){  
    this.firstName =  firstName;  
    this.lastName = lastName;          
}    
  
var Saad = new Person(“Saad”, “Mousliki”);  
 
5.应当小心使用typeof、instanceof和constructor
[js] view plaincopy
var arr = [“a”, “b”, “c”];  
typeof arr;   // return “object”   
arr  instanceof Array // true  
arr.constructor();  //[]  
 
6.创建一个Self-calling函数
       这通常会被称为自我调用的匿名函数或立即调用函数表达式(LLFE)。当函数被创建的时候就会自动执行,好比下面这个:
 
[js] view plaincopy
(function(){  
    // some private code that will be executed automatically  
})();    
(function(a,b){  
    var result = a+b;  
    return result;  
})(10,20)  
 
7.给数组创建一个随机项
[js] view plaincopy
var items = [12, 548 , ‘a’ , 2 , 5478 , ‘foo’ , 8852, , ‘Doe’ , 2145 , 119];  
  
var  randomItem = items[Math.floor(Math.random() * items.length)]; 
 
8.在特定范围里获得一个随机数
下面这段代码非常通用,当你需要生成一个假的数据用来测试时,比如在最低工资和最高之前获取一个随机值。
 
[js] view plaincopy
var x = Math.floor(Math.random() * (max – min + 1)) + min;  
 
9.在数字0和最大数之间生成一组随机数
[js] view plaincopy
var numbersArray = [] , max = 100;  
  
for( var i=1; numbersArray.push(i++) < max;);  // numbers = [0,1,2,3 … 100]   
 
10.生成一组随机的字母数字字符
[js] view plaincopy
function generateRandomAlphaNum(len) {  
    var rdmstring = “”;  
    for( ; rdmString.length < len; rdmString  += Math.random().toString(36).substr(2));  
    return  rdmString.substr(0, len);  
  
}  
 
11.打乱数字数组
[js] view plaincopy
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];  
numbers = numbers.sort(function(){ return Math.random() – 0.5});  
/* the array numbers will be equal for example to [120, 5, 228, -215, 400, 458, -85411, 122205]  */  
 
12.字符串tim函数
trim函数可以删除字符串的空白字符,可以用在Java、C#、PHP等多门语言里。
 
[js] view plaincopy
String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, “”);};    
 
13.数组追加
[js] view plaincopy
var array1 = [12 , “foo” , {name “Joe”} , -2458];  
  
var array2 = [“Doe” , 555 , 100];  
Array.prototype.push.apply(array1, array2);  
/* array1 will be equal to  [12 , “foo” , {name “Joe”} , -2458 , “Doe” , 555 , 100] */  
 
14.将参数对象转换为数组 
[js] view plaincopy
var argArray = Array.prototype.slice.call(arguments);  
 
15.验证一个给定参数是否为数字
[js] view plaincopy
function isNumber(n){  
    return !isNaN(parseFloat(n)) && isFinite(n);  
}  
 
16.验证一个给定的参数为数组
[js] view plaincopy
function isArray(obj){  
    return Object.prototype.toString.call(obj) === ‘[object Array]’ ;  
}  
注意,如果toString()方法被重写了,你将不会得到预期结果。 
或者你可以这样写:
 
[js] view plaincopy
Array.isArray(obj); // its a new Array method  
同样,如果你使用多个frames,你可以使用instancesof,如果内容太多,结果同样会出错。 
[js] view plaincopy
var myFrame = document.createElement(‘iframe’);  
document.body.appendChild(myFrame);  
  
var myArray = window.frames[window.frames.length-1].Array;  
var arr = new myArray(a,b,10); // [a,b,10]    
  
// instanceof will not work correctly, myArray loses his constructor   
// constructor is not shared between frames  
arr instanceof Array; // false  
 
17.从数字数组中获得最大值和最小值
[js] view plaincopy
var  numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];   
var maxInNumbers = Math.max.apply(Math, numbers);   
var minInNumbers = Math.min.apply(Math, numbers);  
 
18.清空数组
[js] view plaincopy
var myArray = [12 , 222 , 1000 ];    
myArray.length = 0; // myArray will be equal to [].  
 
19.不要用delete从数组中删除项目
开发者可以使用split来代替使用delete来删除数组项。与其删除数组中未定义项目,还不如使用delete来替代。 
[js] view plaincopy
var items = [12, 548 ,’a’ , 2 , 5478 , ‘foo’ , 8852, , ‘Doe’ ,2154 , 119 ];   
items.length; // return 11   
delete items[3]; // return true   
items.length; // return 11   
/* items will be equal to [12, 548, “a”, undefined × 1, 5478, “foo”, 8852, undefined × 1, “Doe”, 2154,       119]   */  
也可以……
[js] view plaincopy
var items = [12, 548 ,’a’ , 2 , 5478 , ‘foo’ , 8852, , ‘Doe’ ,2154 , 119 ];   
items.length; // return 11   
items.splice(3,1) ;   
items.length; // return 10   
/* items will be equal to [12, 548, “a”, 5478, “foo”, 8852, undefined × 1, “Doe”, 2154,       119]   */  
delete方法应该删除一个对象属性。 
 
20.使用length属性缩短数组
 
如上文提到的清空数组,开发者还可以使用length属性缩短数组。
 
[js] view plaincopy
var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];    
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].  
 
       如果你所定义的数组长度值过高,那么数组的长度将会改变,并且会填充一些未定义的值到数组里,数组的length属性不是只读的。
 
[js] view plaincopy
myArray.length = 10; // the new array length is 10   
myArray[myArray.length – 1] ; // undefined

90 Responses to “ 20个超实用的JavaScript技巧及最佳实践 ”

  1. chocopie说道:

    gYSXlR Never Ignore The significance Of Extras Like Speaker systems

  2. Thanks for sharing, this is a fantastic article.Thanks Again.

  3. Usually I don at read post on blogs, however I wish to say that this write-up very compelled me to check out and do so! Your writing taste has been amazed me. Thank you, quite nice article.

  4. fraud说道:

    Yay google is my world beater assisted me to find this great site!.

  5. Last week I dropped by this internet site and as usual wonderful content and suggestions. Enjoy the lay out and color scheme

  6. The Venus Factor说道:

    It as great that you are getting thoughts from this piece of writing as well as from our argument made here.

  7. porn说道:

    Of course, what a fantastic blog and illuminating posts, I definitely will bookmark your site.Best Regards!

  8. amsterdam escort说道:

    Looking forward to reading more. Great blog.Thanks Again. Cool.

  9. Wow, fantastic blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is wonderful, as well as the content!

  10. Very neat article post.Thanks Again. Will read on

  11. There is apparently a lot to identify about this. I think you made certain good points in features also.

  12. Wow, great article post.Really looking forward to read more. Really Cool.

  13. crypto说道:

    What as up everyone, it as my first visit at this web page, and piece of writing is really fruitful designed for me, keep up posting these content.

  14. tank fit-up说道:

    I value the article.Really thank you! Will read on

  15. Way cool! Some very valid points! I appreciate you writing this post and also the rest of the site is really good.

  16. What as up, I log on to your blogs on a regular basis. Your humoristic style is awesome, keep it up!

  17. Yay google is my king aided me to find this great web site !.

  18. You ave made some really good points there. I checked on the net to learn more about the issue and found most individuals will go along with your views on this website.

  19. The Lost Ways说道:

    There as definately a great deal to learn about this subject. I love all the points you made.

  20. to say thank you for a remarkable post and a all round thrilling blog (I also love the theme/design),

  21. escort amsterdam说道:

    pretty beneficial gear, on the whole I imagine this is laudable of a bookmark, thanks

  22. sydney escorts说道:

    Your style is so unique compared to other people I ave read stuff from. I appreciate you for posting when you have the opportunity, Guess I all just book mark this page.

  23. pasadena realtor说道:

    If you have any recommendations, please let me know. Thanks!

  24. Indiatimes.com说道:

    I really liked your article post.Thanks Again. Awesome.

  25. Woh I enjoy your content , saved to bookmarks!

  26. Latest Politics说道:

    Really good information can be found on web blog.

  27. 먹튀 검증说道:

    themselves, especially contemplating the reality that you simply might have completed it if you ever decided. The pointers also served to provide an excellent technique to

  28. 먹튀 폴리스说道:

    sky vegas mobile view of Three Gorges | Wonder Travel Blog

  29. This blog is really entertaining additionally amusing. I have picked up a bunch of helpful advices out of it. I ad love to come back again and again. Thanks!

  30. They replicate the worldwide attraction of our dual Entire world Heritage sectors which have been attributed to boosting delegate figures, she said.

  31. Really informative blog article. Much obliged.

  32. Wonderful post, you have pointed out some amazing details , I besides believe this s a really excellent web site.

  33. generic levitra说道:

    Thanks so much for the article.Thanks Again. Much obliged.

  34. Yay google is my queen assisted me to find this great internet site!.

  35. There is noticeably a bunch to get on the subject of this. I deem you completed various fantastically good points in skin texture also.

  36. cheap mp3说道:

    This paragraph regarding SEO presents clear idea designed for new SEO visitors that how to do SEO, therefore keep it up. Pleasant work

  37. May说道:

    Simple but very precise information Thank you for sharing this

  38. Im thankful for the blog article. Keep writing.

  39. 릴게임说道:

    Thanks a lot for sharing this with all of us you actually know what you are talking about! Bookmarked. Kindly also visit my web site =). We could have a link exchange agreement between us!

  40. TSC说道:

    sneak a peek at this site WALSH | ENDORA

  41. 토토사이트说道:

    Im no pro, but I feel you just made an excellent point. You definitely know what youre talking about, and I can seriously get behind that. Thanks for being so upfront and so sincere.

  42. Muchos Gracias for your blog post.Thanks Again. Really Great.

  43. Muchos Gracias for your blog.Really thank you! Much obliged.

  44. this post reminds me of my old room mate! He always kept

  45. 바다 이야기说道:

    You made some decent points there. I looked on the internet for that problem and located most individuals will go together with with the web site.

  46. 다잡아说道:

    Thank you for your article post.Much thanks again. Fantastic.

  47. the same time as searching for a comparable subject, your web site got here up,

  48. When I look at your blog site in Firefox, it looks fine but when opening in Internet Explorer, it has some

  49. Regina SEO说道:

    when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that,

  50. Wow! Thank you! I always wanted to write on my website something like that. Can I take a portion of your post to my site?

  51. Really informative blog.Really thank you! Awesome.

  52. 토토 사이트说道:

    Thanks for sharing, this is a fantastic article post.Really thank you! Fantastic.

  53. You could definitely see your enthusiasm in the work you write. The sector hopes for more passionate writers like you who aren at afraid to say how they believe. At all times go after your heart.

  54. Wow! Thank you! I continually needed to write on my blog something like that. Can I include a part of your post to my website?

  55. 토토 사이트说道:

    Thanks for the post.Thanks Again. Really Cool.

  56. Remarkable things here. I am very satisfied to look your article.

  57. Im thankful for the article.Really thank you! Cool.

  58. Some really select content on this site, saved to bookmarks.

  59. 다잡아说道:

    Utterly pent content material , appreciate it for selective information.

  60. 바다 이야기说道:

    You need to be a part of a contest for one of the highest quality websites online.

  61. Some truly great posts on this internet site , regards for contribution.

  62. personally recommend to my friends. I am confident they will be benefited from this site.

  63. I value the blog article.Thanks Again. Really Great.

  64. This site was how do you say it? Relevant!! Finally I ave found something which helped me. Kudos!

  65. I really liked your blog post.Really thank you! Awesome.

  66. wow, awesome post.Really looking forward to read more. Will read on…

  67. This website was how do you say it? Relevant!! Finally I have found something which helped me. Many thanks!

  68. nfc chto jeto说道:

    Some really marvelous work on behalf of the owner of this site, great content.

  69. punto说道:

    Strange , your posting shows up with a dark color to it, what color is the primary color on your webpage?

  70. Wow, great article.Really looking forward to read more. Cool.

  71. Just wanna input that you have a very nice web site , I like the layout it really stands out.

  72. Venus Factor说道:

    Thanks for sharing, this is a fantastic post.Thanks Again. Cool.

  73. Rattling fantastic info can be found on site.

  74. interest not fake then, about one hour in the

  75. small seo tool说道:

    wow, awesome article.Really thank you! Awesome.

  76. 먹튀검증단说道:

    Thanks-a-mundo for the article. Want more.

  77. 토토사이트说道:

    I really liked your blog post.Thanks Again. Really Cool.

  78. 바다 이야기说道:

    very nice put up, i definitely love this web site, carry on it

  79. 토토 사이트说道:

    My brother recommended I might like this blog. He used to be totally right.

  80. Im grateful for the blog post.Much thanks again.

  81. Incredible points. Solid arguments. Keep up the great effort.

  82. 먹튀검증说道:

    Michael Kors Grayson Will Make You A Noble Person WALSH | ENDORA

  83. 토토사이트说道:

    Major thankies for the post.Thanks Again. Want more.

  84. You might have some genuine insight. Why not hold some kind of contest for your readers?

  85. that type of information in such a perfect means of writing?

  86. free porn说道:

    Some truly good content on this internet site , thanks for contribution.

  87. tarot tirada de cartas tarot tirada si o no

  88. 먹튀폴리스说道:

    This is one awesome article post. Really Great.

  89. the sleeping bag which is designed to make

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>