1.不要在同一行声明多个变量
var a = null; var b = 0; var c = undefined;
这样更好:
var a = null;
b = 0;
c = undefind
2.请使用 ===/!==来比较true/false或者数值,防止JavaScript语言中一些强制类型转换
var a = 1;
var b = '2';
if(a === b){
console.log(a);
}else{
console.log(b);
}
3.使用字面量代替new Array()这种形式
不推荐:
var a = new Array(x1,x2,x3);
//如果x1是一个自然数,那么它的长度将为x1;如果x1不是一个自然数,那么它的长度将为1
//如果将代码传参从两个变为一个,那数组很有可能发生意料不到的长度变化
推荐
var arr = [];
4.不要使用全局函数
不推荐 :
var x = 10,
y = 100;
console.log(window.x + ' ' +window.y)
推荐;(funciton(window){
' use strict';
var x = 10,
y = 100;
console.log(window.x + ' ' +window.y)
}(window));
5.Switch必须使用default分支
switch(num){
case 1:
num++;
break;
case 2:
num--;
break;
case 3:
num = 0;
break;
default:
num = 1;
}
6.函数不应该有时候有返回值,有时候没有返回值(建议最好都要有返回值:undefined)
function(){ return undefined}
7.for循环和if语句必须使用花括号
for(var i=0 ;i<10; i++){
console.log(i);
}
8.for in 循环中的变量 应该使用var 关键字限定作用域,从而避免作用域污染
for(var i in obj){
console.log(obj);
}