JavaScript代码规范总结

//直接放进来代码都没了,格式有乱了,请见谅!
//---------

1 - BoundOrAssignedEvalOrArguments
描述
"eval" and "arguments" must not be bound or assigned
严重性
CRITICAL
错误现象示例
eval = 17;
arguments++; 
++eval; 
var obj = { set p(arguments) { } }; 
var eval; 
try { } catch (arguments) { } 
修复建议
//不要修改eval和arguments
2 - FunctionDeclarationsWithinBlocks
描述
Do not use function declarations within blocks
严重性
BLOCKER
错误现象示例
if(x){
  function foo() {}
} 
修复建议
if(x){
  var foo = function() {};
} 
3 - DuplicatePropertyName
描述
Duplicate property names not allowed in object literals
严重性
CRITICAL
错误现象示例
vardata ={
'key': 'value',
'key': 'value',
}
修复建议
vardata ={
'key1': 'value',
'key2': 'value',
}
4 - DuplicateFunctionArgument
描述
Function argument names should be unique
严重性
CRITICAL
错误现象示例
function compute(a, a, c) {}
修复建议
function compute(a, b, c) {}
5 - NestedIfDepth
描述
Avoid deeply nested if statements
严重性
MINOR
错误现象示例
function sayHello() {
 if (true) {
  if (true) {
   if (true) {
    if (true) { // Non-Compliant
     return;
    } else {
     return;
    }
   } else if (true) { // Compliant
    if (true) { // Non-Compliant
     return;
    }
   }
  }
 }
}
修复建议
//尽量减少if语句的嵌套层次,最多不要超过5层
6 - ConstructorFunctionsForSideEffects
描述
Avoid use of constructor functions for side-effects
严重性
MINOR
错误现象示例
new 
MyConstructor();
修复建议
var something
 = new MyConstructor();
7 - Eval
描述
Avoid use of eval
严重性
MINOR
错误现象示例
ar myCode = 
'alert('Howdy?');';eval(myCode); 
修复建议
//避免使用eval函数,如果在页面上有使用eval()函数,就需要特别正确的方式保证它正常执行。
8 - CommentedCode
描述
Sections of code should not be "commented out"
严重性
MINOR
错误现象示例
//isValid(element);
修复建议
//代码段不该被注释掉,无用代码应删除
9 - SingleQuote
描述
Use single quote for string literals
严重性
MINOR
错误现象示例
var firstParameter
 = “something”;
修复建议
//使用单引号效率更高
var secondParameter 
= 'somethingElse';
10 - CurlyBraces
描述
Always use curly braces for if/else/for/while/do statements
严重性
MAJOR
错误现象示例
if (i> arr.length)
 continue;
修复建议
//if/else/for/while/do语句都应使用花括号
if (i> arr.length){
 continue;
}
11 - NonEmptyCaseWithoutBreak
描述
An unconditional break statement shall terminate every non-empty switch-clause
严重性
MAJOR
错误现象示例
switch (param) {
case 0:
doSomething();
case 1:
doOtherthing();
default: 
doSomethingElse();
}
修复建议
switch (param) {
case 0:
doSomething();
break;
case 1:
case 2:
doOtherthing();
break;
default: 
doSomethingElse();
break;
} 
//注意:空的case语句允许指定相同的行为
12 - FunctionDefinitionInsideLoop
描述
Avoid definition of functions inside loops
严重性
MAJOR
错误现象示例
var funs = [];
for (var i = 0; i < 13; i++) {
funs[i] = function() { 
return i;
};
}
修复建议
//不要在循环中定义函数,可以在循环外定义函数,然后在循环中调用,
//也可以将循环中的函数改为自执行的。
var funs = [];
for (var i = 0; i < 13; i++) {
funs[i] = (function(j) { 
return function(){
return j;
};
})(i);
}
13 - AssignmentWithinCondition
描述
Avoid doing assignments in the condition part of if/while/for statements
严重性
MAJOR
错误现象示例
if (dayNumber = getClickedDayNumber(dayInfo)) { 
alert('day number found : ' + dayNumber);
} 
修复建议
var value = someFunction();
if (value === true) {
   doSomething();
} 
14 - EmptyBlock
描述
Avoid empty block
严重性
MAJOR
错误现象示例
try{
  if (something) { 
  }
}catch(e) {
}
修复建议
//不要出现空的if/for/while代码块,这里最常见的应该是catch中可能为空,
//catch中如果不知道怎么操作,可以记录错误信息或给变量赋初始值等操作
try{
  if (something) { 
     doSomething();
  }
}catch(e) {
  log.info('异常信息:' + e.getMessage());
} 
15 - ExcessiveParameterList
描述
Avoid function with too many parameters
严重性
MAJOR
错误现象示例
function dateRuleResultDetail(ruleName, ruleNo, beforeCabinCheck, 
afterCabinCheck, orgfltdatestart, orgfltdateend, destfltdatestart, 
destfltdateend, activeflag) { 
} 
修复建议
//obj是一个对象,包括的属性有:ruleName, ruleNo, beforeCabinCheck, 
//afterCabinCheck, orgfltdatestart, orgfltdateend, destfltdatestart,
// destfltdateend, activeflag
function(obj) {
//do something
} 
16 - NamedFunctionExpression
描述
Avoid named function expressions
严重性
MAJOR
错误现象示例
var f = function fun(){};
修复建议
var f = function() {};
17 - RedeclaredFunction
描述
Avoid redeclaration of functions
严重性
MAJOR
错误现象示例
fun(); // prints 'bar'
// first declaration of the function
function fun() {
print('foo');
}
fun(); // prints 'bar'
// redeclaration of the 'fun' function: this definition overrides the previous one
function fun() {
print('bar');
}
fun(); // prints 'bar' 
修复建议
//在同一作用域范围内不要重复声明函数。代码定义了两个同名的fun函数,不论在哪里调用fun函数,
//后面定义的都会覆盖掉前面定义的。
18 - UnusedFunctionArgument
描述
Avoid unused function arguments
严重性
MAJOR
错误现象示例
/ Non-Compliant as 'a' argument is not used
function fun(a, b) { 
var result = b / 3;
return b;
} 
修复建议
function fun(b) { 
var result = b / 3;
return b;
} 
19 - UnusedVariable
描述
Avoid unused variables
严重性
MAJOR
错误现象示例
function fun(a, b) {
// Non-Compliant as c is never used
var c = 2; 
return a + b;
}
fun(1, 2); 
修复建议
function fun(a, b) {
return a + b;
}
fun(1, 2); 
20 - SameNameForFunctionAndVariable
描述
Avoid usage of the same name for the declarations of both a function and a variable
严重性
MAJOR
错误现象示例
var fun;
function fun() {}
修复建议
var fun = function () {}
//对于这种问题,我们只需要保证变量名和函数名不同即可。
21 - EqEqEq
描述
Avoid use of == and != in favor of === and !==
严重性
MAJOR
错误现象示例
if (1 == '1') {
console.log('变量类型相同且值也相等.'); 
} else {
console.log('变量类型不同或值不相等.');
} 
修复建议
if (1 === '1') {
console.log('变量类型相同且值也相等.'); 
} else {
console.log('变量类型不同或值不相等.');
}
22 - ContinueStatement
描述
Avoid using 'continue' branching statement
严重性
MAJOR
错误现象示例
mylabel: for (i = 0 ; i < 3; i++) {
for (j = 0; j < 4 ; j++) {
doSomething();
if (checkSomething()) {
continue mylabel; 
}
}
} 
修复建议
for (i = 0 ; i < 3; i++) {
for (j = 0; j < 4 ; j++) {
doSomething();
if (checkSomething()) {
break;
}
}
} 
23 - VariableShadowing
描述
Avoid variable shadowing
严重性
MAJOR
错误现象示例
//情况一
functionshow(point,element){
if(!this.drops.length){
return;
}
vardrop,affected =[];
// Non-Compliant as the 'drop' parameter is not 
//the one defined one line before even if it looks like
this.drops.each(function(drop){
if(Droppables.isAffected(point,element,drop))
affected.push(drop);
});
//情况二
varcancel ='cancel';
Person.prototype.getName =function(){
varcancel =this;
.......
if(true){
varcancel ='name';
......
}
}
修复建议
//避免变量覆盖。
24 - CollapsibleIfStatements
描述
Collapsible If statements
严重性
MAJOR
错误现象示例
if(condition1){
if(condition2){
doSomething();
}
}
修复建议
//多个条件可以组合在一起的尽量组合。
if(condition1 && condition2){
   doSomething();
}
25 - DebuggerStatement
描述
Debugger statement must not be used
严重性
MAJOR
错误现象示例
for(vari =1;i<5;i++){
// Print i to the Output window.
Debug.write('loop index is '+i);
// Wait for user to resume.
debugger;
}
修复建议
//源码中不要使用调试语句。
26 - VariableDeclarationAfterUsage
描述
Declare variables before usage
严重性
MAJOR
错误现象示例
console.log(b);
b =5;
console.log(b);
修复建议
var b;
console.log(b);
b =5;
console.log(b);
27 - HtmlComments
描述
Do not use HTML-style comments
严重性
MAJOR
错误现象示例
<!-- Non-Compliant<!-- Non-Compliant -->
修复建议
//不要使用HTML风格的注释
// Compliant/* Compliant */
28 - ConditionalComment
描述
Do not use Internet Explorer's conditional comments
严重性
MAJOR
错误现象示例
/*@cc_on
@if (@_jscript_version >= 5.5)
document.write("You are using IE5.5 or newer");
@else
document.write("You are using IE5 or older");
@end
@*/
修复建议
//不要使用IE浏览器的条件注释。
29 - TooManyBreakOrContinueInLoop
描述
Do not use more than one break or continue statement in loops.
严重性
MAJOR
错误现象示例
for(i=0;i <10;i++){
if(i%n ===0){
break;
}
if(n%i ===0){
continue;
}
}
修复建议
for(i=0;i <10;i++){

if  (i  %   n ===   0)  {
break;
}
}
30 - OneStatementPerLine
描述
Do not use more that one statement per line
严重性
MAJOR
错误现象示例
var foo ='something',
bar ='somethingElse';
修复建议
varf oo ='something';var bar ='somethingElse';
// Non-Compliant - there are two statements
31 - PrimitiveWrappers
描述
Do not use wrapper objects for primitive types
严重性
MAJOR
错误现象示例
var x = new Boolean(false);if (x) {  alert('hi');  // Shows 'hi'.}
修复建议
//尽量不要对原始数据类型使用包装对象,即不要newString,newBoolean等。
32 - DuplicatedBlocks
描述
Duplicated blocks
严重性
MAJOR
错误现象示例
避免多次出现重复的代码块。
修复建议
//将多次重复的代码块抽取成一个公用的方法,减少代码的重复率,也便于后期维护。
33 - Semicolon
描述
Each statement must end with a semicolon
严重性
MAJOR
错误现象示例
// define a function
var fn = function () {
} // semicolon missing at this line
// then execute some code inside a closure
(function () {
})();
//经过编译以后的代码:
var fn = function () {
}(function () {
})(); 
修复建议
// define a function
var fn = function () {
};
// then execute some code inside a closure
(function () {
})();
//经过编译以后的代码:
var fn = function () {
};
(function () {
})(); 
34 - ForIn
描述
For-in statement must filter items
严重性
MAJOR
错误现象示例
function Person(name, age) {
this.name = name;
this.age = age;
}
Object.prototype.sex = 'M';
var person = new Person();
for(var p in person) {
console.log(p);
} 
//输出:name age sex 
修复建议
function Person(name, age) {
this.name = name;
this.age = age;
}
Object.prototype.sex = 'M';
var person = new Person();
for(var p in person) {
if (person.hasOwnProperty(p)) {
console.log(p);
}
} 
//输出:name age 
35 - ParsingError
描述
JavaScript parser failure
严重性
MAJOR
错误现象示例
修复建议
//遵循JavaScript编码规范。
36 - LabelPlacement
描述
Only while/do/for statements can be labelled
严重性
MAJOR
错误现象示例
label:
if(i %2===0)    {
if(i ===12) {
print('12');
break label;
}
print('Odd number, but not 12');
}   

修复建议
loop:
for(var i =0;i <10;i++){
print('Loop');
break loop;
}   

37 - CommentRegularExpression
描述
Regular expression on comment
严重性
MAJOR
错误现象示例
修复建议
//JavaScript代码中的注释应遵循编码规范中的要求。
38 - SwitchWithoutDefault
描述
The final clause of a switch statement shall be the default-clause
严重性
MAJOR
错误现象示例
switch (param) {
case 0:
doSomething();
break;
case 1:
doSomethingElse();
break;
} 
修复建议
switch (param) {
case 0:
doSometElse();
break;
case 1:
doSomethingElse();
break;
default: 
hingElse();
break;
} 
39 - TrailingComma
描述
Trailing comma
严重性
MAJOR
错误现象示例
varsettings ={
'foo':'name',

'bar':'rab',

};  

修复建议
varsettings ={
'foo':  'name',
'bar':'rab'
};  

40 - UnreachableCode
描述
Unreachable code
严重性
MAJOR
错误现象示例
function sayHello() {
if (true) {
return;
// Non-Compliant - this will never be executed
var b; 
} else {
var c;
}
while (true) {
break;
// Non-Compliant - this will never be executed
var d; 
}
} 
修复建议
function sayHello() {
if (true) {
return;
} else {
var c;
}
while (true) {
break;
}
} 
41 - WithStatement
描述
With statement must not be used
严重性
MAJOR
错误现象示例
with (foo) {  var x = 3;  return x;}
修复建议
//不要使用with
42 - TrailingWhitespace
描述
Avoid trailing whitespaces
严重性
INFO
错误现象示例
var str =   'Hello \
World'; 

修复建议
//在一行语句的结尾部分不要添加空格
43 - StrictMode
描述
Use Javascript strict mode with caution
严重性
INFO
错误现象示例
function strict(){
'use strict';
//do something();

}   

修复建议
//避免出现兼容性问题,不要使用'use strict'
 

 

猜你喜欢

转载自just4java.iteye.com/blog/2280164