您的位置:首页 > Web前端 > JavaScript

javascript最佳实践

2016-12-12 10:38 183 查看


转载自:http://www.2cto.com/kf/201401/271807.html


1. 当第一次指定一个变量时,不要忘记使用 var :

指定一个未声明的变量,不使用var时,会声明成全局变量,避免全局变量;


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. undefined, null, 0, false, NaN, ''(空字符串) 都是false;


4. 在每一行的结束使用分号;


5. 创建一个 object constructor:

function Person(firstName, lastName){
this.firstName =  firstName;
this.lastName = lastName;
}

var Saad = new Person(Saad, Mousliki);



6. 小心使用 typeof, instanceof 和 constructor:

var arr = [a, b, c];
typeof arr;   // return object
arr  instanceof Array // true
arr.constructor();  //[]



7. 创建一个自我调用函数:

这通常被称为匿名函数或立即执行函数(Immediately Invoked Function Expression)。 它会在你创建的时候执行,格式如下:
(function(){
// some private code that will be executed automatically
})();
(function(a,b){
var result = a+b;
return result;
})(10,20)



8. 随机获取数组中的一个项:

var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];

var  randomItem = items[Math.floor(Math.random() * items.length)];



9. 在指定范围中获取一个随机数:

这段代码在你试图生成一些假的数据作为测试时很有用:
var x = Math.floor(Math.random() * (max - min + 1)) + min;



10. 生成一个数字数组:

var numbersArray = [] , max = 100;

for( var i=1; numbersArray.push(i++) < max;);  // numbers = [0,1,2,3 ... 100]



11. 生成一组随机的数字和字母组合:

function generateRandomAlphaNum(len) {
var rdmString = ;
for( ; rdmString.length < len; rdmString  += Math.random().toString(36).substr(2));
return  rdmString.substr(0, len);
}



12. 对数字数组洗牌:

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]  */



13. 字符串 trim函数:

Javascript中没有像Java,c#PHP中的清除字符串空格的函数,因此我们可以把它加到String
对象中:
String.prototype.trim = function(){return this.replace(/^s+|s+$/g, );};



14. 将一个数组附加到另一个数组:

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] */



15. 数组中的 argments 参数:

var argArray = Array.prototype.slice.call(arguments);



16. 验证一个参数是不是数值:

function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}



17. 验证一个参数是不是数组:

function isArray(obj){
return Object.prototype.toString.call(obj) === '[object Array]' ;
}
Note that if the toString() method is overridden, you will not get the expected result using this trick.

Or use…

Array.isArray(obj); // its a new Array method
You could also use instanceof if you are not working with multiple frames. However, if you have many contexts, you will get a wrong result.

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



18. 获取一个数字数组中的最大/最小值:

var  numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);



19. 清空数组:

var myArray = [12 , 222 , 1000 ];
myArray.length = 0; // myArray will be equal to [].



20. 不要使用delete来移除数组中的项:

使用split而不是delete来删除数组中的项。 使用delete会将指定的item替换为undefined,而不是将它移除出数组;
不要使用
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 方法应该用来删除一个object的属性


21. 使用length来截取数组:

var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].

myArray.length = 10; // the new array length is 10
myArray[myArray.length - 1] ; // undefined



22. 使用逻辑运算符做条件处理:

var foo = 10;
foo == 10 && doSomething(); // 等同于 if (foo == 10) doSomething();
foo == 5 || doSomething(); // 等同于 if (foo != 5) doSomething();

逻辑运算符|| 也可以用来为方法参数设置默认值

function doSomething(arg1){
arg1 = arg1 || 10; // arg1 将会把10作为默认值如果它没有被设定
}



23. 使用map() 方法遍历数组:

var squares = [1,2,3,4].map(function (val) {
return val * val;
});
// squares will be equal to [1, 4, 9, 16]



24. 保留几位小数:

var num =2.443242342;
num = num.toFixed(4);  // num will be equal to 2.4432



25. 浮点型问题:

0.1 + 0.2 === 0.3 // is false
9007199254740992 + 1 // is equal to 9007199254740992
9007199254740992 + 2 // is equal to 9007199254740994

你可以使用toFixed() 和 toPrecision() 来解决这个问题;


26. 使用循环时,检查object的属性:

for (var name in object) {
if (object.hasOwnProperty(name)) {
// do something with name
}
}



27. 逗号操作符:

var a = 0;
var b = ( a++, 99 );
console.log(a);  // a will be equal to 1
console.log(b);  // b is equal to 99



28. 缓存变量:

var navright = document.querySelector('#right');
var navleft = document.querySelector('#left');
var navup = document.querySelector('#up');
var navdown = document.querySelector('#down');



29. 在传入isFinite() 前验证参数:

isFinite(0/0) ; // false
isFinite(foo); // false
isFinite(10); // true
isFinite(10);   // true
isFinite(undifined);  // false
isFinite();   // false
isFinite(null);  // true  !!!



30. 在数组中避免负向索引:

var numbersArray = [1,2,3,4,5];
var from = numbersArray.indexOf(foo) ;  // from is equal to -1
numbersArray.splice(from,2);    // will return [5]



31. (使用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  */



32. 避免使用eval()或Function构造函数:

var func1 = new function(functionCode);
var func2 = eval(functionCode);



33. 避免使用with()方法:

如果在全局区域里使用with()插入变量的话,万一有一个变量名字和它名字一样,就很容易混淆和重写


34. 避免在数组里使用for-in loop:

不使用:
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++)
为什么?数组长度arraynNumbers在每次loop迭代时都会被重新计算,



35. 不要向setTimeout()和setInterval()方法里传递字符串:

如果在这两个方法里传递字符串,那么字符串会像eval那样重新计算,这样速度就会变慢。
不要使用:
setInterval('doSomethingPeriodically()', 1000);
setTimeOut('doSomethingAfterFiveSeconds()', 5000);

使用:
setInterval(doSomethingPeriodically, 1000);
setTimeOut(doSomethingAfterFiveSeconds, 5000);



36. 使用switch/case语句代替较长的if/else语句:


37. 遇到数值范围时,可以选用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



38. 创建一个对象,该对象的属性是一个给定的对象:

function clone(object) {
function OneShotConstructor(){};
OneShotConstructor.prototype= object;
return new OneShotConstructor();
}
clone(Array).prototype ;  // []



39. 一个HTML escaper函数:

function escapeHTML(text) {
var replacements= {<: <, >: >,&: &, : };
return text.replace(/[<>&]/g, function(character) {
return replacements[character];
});
}



40. 在一个loop里避免使用try-catch-finally:


41. 给XMLHttpRequests设置timeouts:

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();



42. 处理WebSocket超时:

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);
}
}



43. 最原始的操作要比函数调用快:

var min = Math.min(a,b);
A.push(v);

使用
var min = a < b ? a b;
A[A.length] = v;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息