大家都知道,全世界來說JavaScript是超流行的編程語言之一,開發者用它不僅可以開發出炫麗的Web程序,還可以用它來開發一些移動應用程序(如 PhoneGap或Appcelerator),甚至是服務端應用,比如NodeJS、Wakanda以及其它實現。此外,許多開發者都會把 JavaScript選爲入門語言,使用它來做一些基本的彈出窗口等。
在本篇文章中,我們將會向大家分享JavaScript開發中的小技巧、最佳實踐和實用內容,不管你是前端開發者還是服務端開發者,都應該來看看這些編程的技巧總結,絕對會讓你受益匪淺的。
文中所提供的代碼片段都已經過最新版的Chrome 30測試,該瀏覽器使用V8 JavaScript引擎(V8 3.20.17.15)。
1.第一次給變量賦值時,別忘記var關鍵字
如果初次賦值給未聲明的變量,該變量會被自動創建爲全局變量,在JS開發中,應該避免使用全局變量,這是大家容易忽略的錯誤。
2.使用===而非==
並且永遠不要使用=或!=。
[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解析器會自動加上。
function Person(firstName, lastName){ this.firstName = firstName; this.lastName = lastName; } var Saad = new Person("Saad", "Mousliki");
5.小心使用typeof、instanceof和constructor
var arr = ["a", "b", "c"]; typeof arr; // return "object" arr instanceof Array // true arr.constructor(); //[]
6.創建一個自調用(Self-calling)函數
通常被稱爲自調用匿名函數或即刻調用函數表達式(LLFE)。當函數被創建的時候就會自動執行,如下:
(function(){ // some private code that will be executed automatically })(); (function(a,b){ var result = a+b; return result; })(10,20)
7.給數組創建一個隨機項
var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119]; var randomItem = items[Math.floor(Math.random() * items.length)];
8.在特定範圍裏獲得一個隨機數
下面這段代碼非常通用,當你需要生成一個測試的數據時,比如在最高工資和最低工資之間獲取一個隨機數的話。
var x = Math.floor(Math.random() * (max - min + 1)) + min;
9.在數字0和最大數之間生成一組隨機數
var numbersArray = [] , max = 100; for( var i=1; numbersArray.push(i++) < max;); // numbers = [0,1,2,3 ... 100]
10.生成一組隨機的字母數字字符
function generateRandomAlphaNum(len) { var rdmstring = ""; for( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2)); return rdmString.substr(0, len); }
11.打亂數字數組
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.字符串trim函數
trim函數可以刪除字符串兩端的空白字符,可以用在Java、C#、PHP等多門語言裏。
String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, "");};
13.數組追加
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.將參數對象轉換爲數組
var argArray = Array.prototype.slice.call(arguments);
15.驗證一個指定參數是否爲數字
function isNumber(n){ return !isNaN(parseFloat(n)) && isFinite(n); }
16.驗證一個給定的參數爲數組
function isArray(obj){ return Object.prototype.toString.call(obj) === '[object Array]' ; }
注意,如果toString()方法被重寫了,你將不會得到預期結果。
或者你可以這樣寫:
Array.isArray(obj); // its a new Array method
同樣,如果你使用多個frames,你可以使用instancesof,如果內容太多,結果同樣會出錯。
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.從數字數組中獲得最大值和最小值
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.清空數組
var myArray = [12 , 222 , 1000 ]; myArray.length = 0; // myArray will be equal to [].
19.不要用delete從數組中刪除項目
開發者可以使用split來替代delete去刪除數組中的項目。好的方式是使用delete去替換數組中undefined的數組項目,而不是使用delete去刪除數組中項目。
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] */
應該如下使用
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屬性截短數組。
var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ]; myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].
如果你所定義的數組長度值過高,那麼數組的長度將會改變,並且會填充一些未定義的值到數組裏,數組的length屬性不是隻讀的。
myArray.length = 10; // the new array length is 10 myArray[myArray.length - 1] ; // undefined
繼續上一部分,這裏是45個JavaScript技巧和最佳實踐的第二部分,如果你沒有閱讀第一篇的話,請在這裏閱讀:
21. 使用邏輯AND/OR來處理條件語句
- var foo = 10;
- foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething();
- foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();
邏輯AND也可以用來設置含糊參數缺省的值
- Function doSomething(arg1){
- Arg1 = arg1 || 10; // arg1 will have 10 as a default value if it’s not already set
- }
22. 使用map()函數方法來循環數組裏的項目
- var squares = [1,2,3,4].map(function (val) {
- return val * val;
- });
- // squares will be equal to [1, 4, 9, 16]
23. 按小數點後N位來四捨五入
- var num =2.443242342;
- num = num.toFixed(4); // num will be equal to 2.4432
24. 浮點問題
- 0.1 + 0.2 === 0.3 // is false
- 9007199254740992 + 1 // is equal to 9007199254740992
- 9007199254740992 + 2 // is equal to 9007199254740994
爲什麼? 0.1 + 0.2 等於 0.30000000000000004 。你應該知道所有的javascript數字在64位2進制內部都是使用浮點表示
這個來自於IEEE 754標準。更多信息介紹,請參考:相關博客
你可以使用上面介紹的toFixed()和toPrecision()來解決這個問題
25. 使用for-in循環來檢查對象的指定屬性
下面的代碼片段非常實用,可以避免從對象的prototype來循環遍歷對象的屬性:
- for (var name in object) {
- if (object.hasOwnProperty(name)) {
- // do something with name
- }
- }
26. 逗號操作符
- var a = 0;
- var b = ( a++, 99 );
- console.log(a); // a will be equal to 1
- console.log(b); // b is equal to 99
27. 緩存需要計算或者DOM查詢的變量
使用jQuery的選擇器,我們一定要記住緩存DOM元素,這樣會提高執行效率:
- var navright = document.querySelector('#right');
- var navleft = document.querySelector('#left');
- var navup = document.querySelector('#up');
- var navdown = document.querySelector('#down');
28. 在傳入isFinite()之前驗證參數
- isFinite(0/0) ; // false
- isFinite("foo"); // false
- isFinite("10"); // true
- isFinite(10); // true
- isFinite(undifined); // false
- isFinite(); // false
- isFinite(null); // true !!!
29. 避免數組中index爲負值
- var numbersArray = [1,2,3,4,5];
- var from = numbersArray.indexOf("foo") ; // from is equal to -1
- numbersArray.splice(from,2); // will return [5]
這裏需要注意indexof的參數 不能爲負值,但是splice可以
30. 序列化和反序列化(用來處理JSON)
- var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };
- var stringFromPerson = JSON.stringify(person);
- /* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}" */
- var personFromString = JSON.parse(stringFromPerson);
- /* personFromString is equal to person object */
31. 避免使用eval或者Function構建器
使用eval或者function構建器是一件非常消耗資源的操作,因爲每次調用script引擎都必須將源代碼轉換爲可執行的代碼
- var func1 = new Function(functionCode); //避免使用!!
- var func2 = eval(functionCode);//避免使用!!
32. 避免使用with()
使用with()可以用來插入一個變量到全局。然而,如果另外一個變量擁有同樣的名字,將會導致非常混亂並且會覆蓋數值
33. 避免在數組中使用for-in循環
不推薦使用:
- var sum = 0;
- for (var i in arrayNumbers) {
- sum += arrayNumbers[i];
- }
如下代碼將會更好:
- var sum = 0;
- for (var i = 0, len = arrayNumbers.length; i < len; i++) {
- sum += arrayNumbers[i];
- }
作爲額外的好處,i和len的實例化都執行一次,因爲都是循環中的第一個語句,但是比下面執行速度更快:
- for (var i = 0; i < arrayNumbers.length; i++)
爲什麼? arrayNumbers的長度在每次循環都計算一次
34. 傳遞函數,而非字符串到setTimeout()和setInterval()中
如果你傳遞一個字符串到setTimeout和setInterval中,處理方式和eval將會類似,速度會很慢,不要使用如下:
- setInterval('doSomethingPeriodically()', 1000);
- setTimeOut('doSomethingAfterFiveSeconds()', 5000);
推薦使用如下
- setInterval(doSomethingPeriodically, 1000);
- setTimeOut(doSomethingAfterFiveSeconds, 5000);
35. 使用switch/case語句而非一系列的if/else
如果多餘兩個條件,使用switch/case將會更快,而且語法更優雅(代碼組織的更好)。對於多餘10個條件的避免使用。
36. 使用switch/case語句處理數值區域
使用如下小技巧處理數值區域:
- function getCategory(age) {
- var category = "";
- switch (true) {
- case isNaN(age):
- category = "not an age";
- break;
- case (age >= 50):
- category = "Old";
- break;
- case (age <= 20):
- category = "Baby";
- break;
- default:
- category = "Young";
- break;
- };
- return category;
- }
- getCategory(5); // will return "Baby"
37. 創建一個prototype是指定對象的對象
使用如下代碼可以生成一個prototype是指定對象的對象:
- function clone(object) {
- function OneShotConstructor(){};
- OneShotConstructor.prototype= object;
- return new OneShotConstructor();
- }
- clone(Array).prototype ; // []
39. 一個HTMLescaper方法
- function escapeHTML(text) {
- var replacements= {"<": "<", ">": ">","&": "&", "\"": """};
- return text.replace(/[<>&"]/g, function(character) {
- return replacements[character];
- });
- }
編譯:當然,前臺處理並不安全,後臺處理更徹底
40. 在循環中避免使用try-catch-finally
不要使用如下代碼:
- var object = ['foo', 'bar'], i;
- for (i = 0, len = object.length; i <len; i++) {
- try {
- // do something that throws an exception
- }
- catch (e) {
- // handle exception
- }
- }
使用這段代碼:
- var object = ['foo', 'bar'], i;
- try {
- for (i = 0, len = object.length; i <len; i++) {
- // do something that throws an exception
- }
- }
- catch (e) {
- // handle exception
- }
40. 設置XMLHttpRequests的timeout
如果一個XHR花費了太多時間,你可以在XHR調用中使用setTimeout來退出連接:
- var xhr = new XMLHttpRequest ();
- xhr.onreadystatechange = function () {
- if (this.readyState == 4) {
- clearTimeout(timeout);
- // do something with response data
- }
- }
- var timeout = setTimeout( function () {
- xhr.abort(); // call error callback
- }, 60*1000 /* timeout after a minute */ );
- xhr.open('GET', url, true);
- xhr.send();
額外的好處,你可以完全避免同步AJAX調用
41. 處理WebSocket timeout
一般來說,當一個websocket連接建立後,服務器可以在30秒無響應的情況下time out你的連接。防火牆也可以做到。
爲了處理timeout問題,你可以定時發送一個空的消息到服務器。爲了實現,你可以添加兩個方法到你的代碼中:
一個保證連接的存在,另外一個取消連接。使用這個技巧,你可以處理timeout問題:
- var timerID = 0;
- function keepAlive() {
- var timeout = 15000;
- if (webSocket.readyState == webSocket.OPEN) {
- webSocket.send('');
- }
- timerId = setTimeout(keepAlive, timeout);
- }
- function cancelKeepAlive() {
- if (timerId) {
- cancelTimeout(timerId);
- }
- }
keepAlive函數可以添加到webSocket的onOpen函數的最後。cancelKeepAlive添加到webSocket的onClose函數最後。
42. 記住,操作符比函數調用更快
不推薦使用:
- var min = Math.min(a,b);
- A.push(v);
推薦使用:
- var min = a < b ? a:b;
- A[A.length] = v;