Eslint规范

  1. for 循环禁止使用无限循环(这个非默认推荐)

    1. // bad
    2. for (var i = 0; i < 10; i--) {
    3. }
    4. for (var i = 10; i >= 0; i++) {
    5. }
    6. // good
    7. for (var i = 0; i < 10; i++) {
    8. }
  2. 不允许和负0比较

    1. // bad
    2. if (x === -0) {
    3. // doSomething()...
    4. }
    5. // good
    6. if (x === 0) {
    7. // doSomething()...
    8. }
    9. if (Object.is(x, -0)) {
    10. // doSomething()...
    11. }
  3. 禁止在条件语句(if,while,do...while )中出现赋值操作

    1. // bad
    2. if (user.jobTitle = "manager") {
    3. // user.jobTitle is now incorrect
    4. }
    5. // good
    6. if (user.jobTitle == "manager") {
    7. // doSomething()...
    8. }

    注意:该规则有个字符串选项,默认是“except-parens”,允许出现赋值操作,但必须是被圆括号括起来的;设置为“always”表示禁止在条件语句中出现赋值语句

    1. // bad 设置为except-parens
    2. var x;
    3. if (x = 0) {
    4. var b = 1;
    5. }
    6. function setHeight(someNode) {
    7. "use strict";
    8. do {
    9. someNode.height = "100px";
    10. } while (someNode = someNode.parentNode);
    11. }
    12. // good 设置为except-parens
    13. var x;
    14. if (x === 0) {
    15. var b = 1;
    16. }
    17. function setHeight(someNode) {
    18. "use strict";
    19. do {
    20. someNode.height = "100px";
    21. } while ((someNode = someNode.parentNode));
    22. }
  4. 禁止在代码中使用console(在产品发布之前,剔除console的调用)

    1. // bad
    2. console.log("Log a debug level message.");
    3. console.warn("Log a warn level message.");
    4. console.error("Log an error level message.")
    5. // good
    6. //自定义的Console
    7. Console.log("Log a debug level message.");

    注意:可以设置allow参数允许console 对象方法

  1. 禁止在条件语句(for,if,while,do...while)和三元表达式(?:)中使用常量表达式

    1. // bad
    2. if (false) {
    3. doSomething();
    4. }
    5. if (2) {
    6. doSomething();
    7. }
    8. for (;-2;) {
    9. doSomething();
    10. }
    11. while (typeof x) {
    12. doSomething();
    13. }
    14. do{
    15. doSomething();
    16. } while (x = -1);
    17. var result = 0 ? a : b;
    18. // good
    19. if (x === 0) {
    20. doSomething();
    21. }
    22. for (;;) {
    23. doSomething();
    24. }
    25. while (typeof x === "undefined") {
    26. doSomething();
    27. }
    28. do{
    29. doSomething();
    30. } while (x);
    31. var result = x !== 0 ? a : b;

    注意:可以通过设置checkLoops参数来表示是否允许使用常量表达式

  2. 禁用debugger,采用断点的方式进行调试

    1. // bad
    2. function isTruthy(x) {
    3. debugger;
    4. return Boolean(x);
    5. }
    6. // good
    7. function isTruthy(x) {
    8. return Boolean(x); // set a breakpoint at this line
    9. }
  3. 不允许在函数(function)定义里面出现重复的参数(箭头函数和类方法设置重复参数会报错,但跟该规则无关)

    1. // bad
    2. function foo(a, b, a) {
    3. console.log("value of the second a:", a);
    4. }
    5. var bar = function (a, b, a) {
    6. console.log("value of the second a:", a);
    7. };
    8. // good
    9. function foo(a, b, c) {
    10. console.log(a, b, c);
    11. }
    12. var bar = function (a, b, c) {
    13. console.log(a, b, c);
    14. };
    15. // 箭头函数报错
    16. function foo(x, x, y = 1) {
    17. //doSomething();
    18. }
    19. // SyntaxError: Duplicate parameter name not allowed in this context
  4. 不允许对象字面量出现重复的key

    1. // bad
    2. var foo = {
    3. bar: "baz",
    4. bar: "qux"
    5. };
    6. var foo = {
    7. "bar": "baz",
    8. bar: "qux"
    9. };
    10. var foo = {
    11. 0x1: "baz",
    12. 1: "qux"
    13. };
    14. // good
    15. var foo = {
    16. bar: "baz",
    17. foo: "foo"
    18. };
  5. 不允许使用重复的case值

    1. // bad
    2. var a = 1;
    3. var b = 1;
    4. switch (a) {
    5. case 1:
    6. break;
    7. case 2:
    8. break;
    9. case 1: // duplicate test expression
    10. break;
    11. default:
    12. break;
    13. }
    14. switch (a) {
    15. case b:
    16. break;
    17. case 2:
    18. break;
    19. case b: // duplicate test expression
    20. break;
    21. default:
    22. break;
    23. }
    24. switch (a) {
    25. case '1':
    26. break;
    27. case 2:
    28. break;
    29. case '1': // duplicate test expression
    30. break;
    31. default:
    32. break;
    33. }
    34. //good
    35. var a = 1;
    36. switch (a) {
    37. case 1:
    38. break;
    39. case 2:
    40. break;
    41. case 3: // duplicate test expression
    42. break;
    43. default:
    44. break;
    45. }
  6. 不允许出现空块语句

    1. // bad
    2. if (foo) {
    3. }
    4. try {
    5. doSomething();
    6. } catch(ex) {
    7. } finally {
    8. }
    9. //good
    10. if (foo) {
    11. // empty
    12. }
    13. try {
    14. doSomething();
    15. } catch (ex) {
    16. // continue regardless of error
    17. }

    注意:可以通过allowEmptyCatch为true允许出现空的catch子句

  7. 不允许在正则表达式中出现空字符集

    1. // bad
    2. /^abc[]/.test("abcdefg"); // false
    3. "abcdefg".match(/^abc[]/); // null
    4. // good
    5. /^abc/.test("abcdefg"); // true
    6. "abcdefg".match(/^abc/); // ["abc"]
    7. /^abc[a-z]/.test("abcdefg"); // true
    8. "abcdefg".match(/^abc[a-z]/); // ["abcd"]
  8. 不允许对catch子句的参数进行重新赋值

    1. // bad
    2. try {
    3. // code
    4. } catch (e) {
    5. e = 10;
    6. }
    7. // good
    8. try {
    9. // code
    10. } catch (e) {
    11. var foo = 10;
    12. }
  9. 禁止不必要的布尔类型转换

    1. // bad
    2. var bar = 'zhinanzhen';
    3. var foo = !!!bar;//与!bar值相同,都为false
    4. var foo = !!bar ? baz : bat;
    5. var foo = Boolean(!!bar);
    6. if (Boolean(foo)) {
    7. // ...
    8. }
    9. // good
    10. var foo = !!bar;//转布尔值
    11. var foo = Boolean(bar);
    12. function foo() {
    13. return !!bar;
    14. }
    15. var foo = bar ? !!baz : !!bat;
  10. 禁止不必要的分号和括号

    1. // bad
    2. var x = 5;;
    3. function foo() {
    4. // code
    5. };
    6. a = (b * c);
    7. // good
    8. var x = 5;
    9. var foo = function() {
    10. // code
    11. }
    12. a = b * c;
  11. 不允许对function重新赋值

    1. // bad
    2. var bar = 5;;
    3. function foo() {}
    4. foo = bar;
    5. function foo() {
    6. foo = bar;
    7. }
    8. // good
    9. var foo = function () {}
    10. foo = bar;
    11. function foo(foo) { // `foo` is shadowed.
    12. foo = bar;
    13. }
    14. function foo() {
    15. var foo = bar; // `foo` is shadowed.
    16. }
  12. 不允许在嵌套的语句块中用var声明变量和function

    1. // bad
    2. if (test) {
    3. function doSomethingElse () {
    4. //code
    5. }
    6. }
    7. // good
    8. function doSomething() {
    9. const a = 1;
    10. }

    注意:

    1. "functions" (默认) 禁止 function 声明出现在嵌套的语句块中
    2. "both" 禁止 function 和 var 声明出现在嵌套的语句块中
  13. 不允许在正则表达式中使用控制字符,即不可显示的字符(在ASCII码中,第0~31号及第127号是控制字符或通讯专用字符)

// bad var pattern1 = /\x1f/; var pattern2 = new RegExp("\x1f");

// good var pattern1 = /\x20/; var pattern2 = new RegExp("\x20");

  1. ```
  1. 不允许RegExp构造函数中出现无效的正则表达式

    1. // bad
    2. RegExp('[');//无效,报错,RegExp('[]')有效
    3. // good
    4. RegExp('.');//'.'元字符查找单个字符
  2. 不允许正则表达式字面量中出现多个空格

    1. // bad
    2. var re = /foo bar/;
    3. // good
    4. var re = /foo {3}bar/;
  3. 定义函数时,空格的使用(参考airbnb规范的30-34条)

    1. // bad
    2. function thing() /*<NBSP>*/{//使用了多个空格
    3. return 'test';
    4. }
    5. function thing( /*<NBSP>*/){
    6. return 'test';
    7. }
    8. // good
    9. function thing() {
    10. return 'test';
    11. }
    12. function thing(/*<NBSP>*/) {
    13. return 'test';
    14. }

    注意:

    1. "skipStrings": true (默认) 允许在字符串字面量中出现任何空白字符
    2. "skipComments": true 允许在注释中出现任何空白字符
    3. "skipRegExps": true 允许在正则表达式中出现任何空白字符
    4. "skipTemplates": true 允许在模板字面量中出现任何空白字符
  4. 不允许将全局对象(这里主要指非函数型和非构造器对象的全局对象,例如:NaN,Infinity,undefined,Math,JSON,Reflect)作为函数进行调用

    1. // bad
    2. var math = Math();
    3. var json = JSON();
    4. var reflect = Reflect();
    5. // good
    6. function area(r) {
    7. return Math.PI * r * r;
    8. }
    9. var object = JSON.parse("{}");
    10. var value = Reflect.get({ x: 1, y: 2 }, "x");
  5. 不允许使用稀疏数组

    1. // bad
    2. var items = [,];
    3. var colors = [ "red",, "blue" ];
    4. // good
    5. var items = [];
    6. var items = new Array(23);
    7. var colors = [ "red", "blue", ];
  6. 不允许使用多行表达式(使用分号结尾,避免无关的两条语句被解析成一条语句)

    1. // bad
    2. var hello = 'world'
    3. [1, 2, 3].forEach(addNumber);
    4. // good
    5. ar hello = 'world';
    6. [1, 2, 3].forEach(addNumber);
  7. 不允许在return,throw,continue,break后出现执行不到的代码

    1. // bad
    2. function foo() {
    3. return true;
    4. console.log("done");
    5. }
    6. // good
    7. function bar() {
    8. let x = 1;
    9. return x;
    10. }
  8. 不允许直接在finally语句中出现控制流语句(return,throw,break,continue)

    1. // bad
    2. let foo = function() {
    3. try {
    4. return 1;
    5. } catch(err) {
    6. return 2;
    7. } finally {
    8. return 3;
    9. }
    10. };
    11. // good
    12. let foo = function() {
    13. try {
    14. return 1;
    15. } catch(err) {
    16. return 2;
    17. } finally {
    18. console.log("hola!");
    19. }
    20. };
    21. //间接使用
    22. let foo = function() {
    23. try {
    24. return 1;
    25. } catch(err) {
    26. return 2;
    27. } finally {
    28. let a = function() {
    29. return "hola!";
    30. }
    31. }
    32. };
  9. 否定操作的使用

    1. // bad
    2. if (!key in object) {
    3. // doSomthing()
    4. }
    5. // good
    6. if (!(key in object)) {
    7. // doSomthing()
    8. }
  10. 检查非数值(NaN)必须使用isNaN()

    1. // bad
    2. if (foo == NaN) {
    3. // doSomthing()
    4. }
    5. // good
    6. if (isNaN(foo)) {
    7. // doSomthing()
    8. }
  11. typeof 表达式必须与有效的字符串进行比较

    1. // bad
    2. typeof foo === "strnig"
    3. typeof foo == "undefimed"
    4. // good
    5. typeof foo === "string"
    6. typeof bar == "undefined"
  12. 不允许在case和default语句中出现词法声明(let,const,function,class),如果需要使用,必须使用花括号

    1. // bad
    2. switch (foo) {
    3. case 1:
    4. let x = 1;
    5. break;
    6. case 2:
    7. const y = 2;
    8. break;
    9. case 3:
    10. function f() {}
    11. break;
    12. default:
    13. class C {}
    14. }
    15. // good
    16. switch (foo) {
    17. // The following case clauses are wrapped into blocks using brackets
    18. case 1: {
    19. let x = 1;
    20. break;
    21. }
    22. case 2: {
    23. const y = 2;
    24. break;
    25. }
    26. case 3: {
    27. function f() {}
    28. break;
    29. }
    30. case 4:
    31. // Declarations using var without brackets are valid due to function-scope hoisting
    32. var z = 4;
    33. break;
    34. default: {
    35. class C {}
    36. }
    37. }
  13. 不允许case语句落空,可以用throw、return、break或者注释作为结束

    1. // bad
    2. switch(foo) {
    3. case 1:
    4. doSomething();
    5. case 2:
    6. doSomethingElse();
    7. }
    8. // good
    9. switch(foo) {
    10. case 1:
    11. doSomething();
    12. break;
    13. case 2:
    14. doSomething();
    15. }
    16. switch(foo) {
    17. //如果有意落空case语句,需设置commentPattern参数,并且加上注释
    18. case 1:
    19. doSomething();
    20. // break omitted
    21. case 2:
    22. doSomethingElse();
    23. }
  14. 不允许使用空的解构模式

    1. // bad
    2. var {} = foo;
    3. var [] = foo;
    4. var {a: {}} = foo;
    5. var {a: []} = foo;
    6. function foo({}) {}
    7. function foo([]) {}
    8. function foo({a: {}}) {}
    9. function foo({a: []}) {}
    10. // good
    11. var {a = {}} = foo;
    12. var {a = []} = foo;
    13. function foo({a = {}}) {}
    14. function foo({a = []}) {}
  15. 不允许修改只读的全局变量

    1. // bad
    2. Object = null;
    3. undefined = 1;
    4. window = {};
  16. 不允许使用8进制字面量(即用0开头的数字)

    1. // bad
    2. var num = 071;
    3. var result = 5 + 07;
    4. // good
    5. var num = "071";
  1. 不允许多次声明同一个变量

    1. // bad
    2. var a = 3;
    3. var a = 10;
    4. // good
    5. var a = 3;
    6. a = 10;

    注意: “builtinGlobals”如果设置为 true,该规则也会检查全局内置对象,比如Object、Array、Number…

  2. 不允许自己给自己赋值

    1. // bad
    2. foo = foo;
    3. [a, b] = [a, b];
    4. [a, ...b] = [x, ...b];
    5. ({a, b} = {a, x});
    6. // good
    7. foo = bar;
    8. [a, b] = [b, a];
    9. let foo = foo;
  3. 不允许使用没有使用过的标签

    1. // bad
    2. A:
    3. for (let i = 0; i < 10; ++i) {
    4. foo();
    5. }
    6. // good
    7. B:
    8. for (let i = 0; i < 10; ++i) {
    9. if (foo()) {
    10. break B;
    11. }
    12. bar();
    13. }
  4. 不允许使用没有必要的转义

    1. // bad
    2. "\'";
    3. '\"';
    4. "\#";
    5. "\e";
    6. `\"`;
    7. `\"${foo}\"`;
    8. `\#{foo}`;
    9. /\!/;
    10. /\@/;
    11. // good
    12. "\"";
    13. '\'';
    14. "\x12";
    15. "\u00a9";
    16. "\371";
    17. "xs\u2111";
    18. `\``;
    19. `\${${foo}\}`;
    20. `$\{${foo}\}`;
    21. /\\/g;
    22. /\t/g;
    23. /\w\$\*\^\./;
  5. 不允许删除变量(严格模式下会报错)

    1. // bad
    2. var x;
    3. delete x;
  6. 不允许使用未声明的变量

    1. // bad
    2. b = 10;
    3. //good
    4. let b = 10;
  7. 定义过的变量都必须被使用


    1. //good
    2. let b = 10;
    3. alert(b);
  8. 不允许使用空格和tab混合缩进(airbnb推荐使用两个空格作为缩进)

  9. 派生类中的构造函数必须调用 super()。非派生类的构造函数不能调用 super()

    1. //bad
    2. class A {
    3. constructor() {
    4. super(); // This is a SyntaxError.
    5. }
    6. }
    7. class A extends B {
    8. constructor() { } // Would throw a ReferenceError.
    9. }
    10. //good
    11. class A {
    12. constructor() { }
    13. }
    14. class A extends B {
    15. constructor() {
    16. super();
    17. }
    18. }
  10. 在派生类构造函数中,不允许在调用super()之前使用this和super

    1. // bad
    2. class A extends B {
    3. constructor() {
    4. this.a = 0;
    5. super();
    6. }
    7. }
    8. class A extends B {
    9. constructor() {
    10. super.foo();
    11. super();
    12. }
    13. }
    14. //good
    15. class A {
    16. constructor() {
    17. this.a = 0; // OK, this class doesn't have an `extends` clause.
    18. }
    19. }
    20. class A extends B {
    21. constructor() {
    22. super();
    23. this.a = 0; // OK, this is after `super()`.
    24. }
    25. }
  11. 不允许修改类声明的变量

    1. // bad
    2. class A { }
    3. A = 0;
    4. class A {
    5. b() {
    6. A = 0;
    7. }
    8. }
    9. //good
    10. let A = class A { }
    11. A = 0; // A is a variable.
    12. let A = class {
    13. b() {
    14. A = 0; // A is a variable.
    15. }
    16. }
  12. 禁止修改const声明的变量

    1. // bad
    2. const a = 0;
    3. a = 1;
    4. //good
    5. const a = 0;
    6. alert(a);
  13. Symbol函数前不能使用new命令

    1. // bad
    2. var foo = new Symbol("foo");
    3. //good
    4. var foo = Symbol("foo");
    5. function bar(Symbol) {
    6. const baz = new Symbol("baz");
    7. }
  14. 不允许使用没有yield的generator 函数

    1. // bad
    2. function* foo() {
    3. return 10;
    4. }
    5. //good
    6. function* foo() {
    7. yield 5;
    8. return 10;
    9. }

Airbnb规范

  1. 使用const声明只读的常量,使用let声明可变的变量

    1. // bad
    2. var a = 1;
    3. var b = 4;
    4. if(b > a){
    5. a += 1;
    6. }
    7. //good
    8. let a = 1;
    9. const b = 2;
    10. if(b > a){
    11. a += 1;
    12. }
  2. 使用字面量创建对象和数组

    1. // bad
    2. const item = new Object();
    3. const items = new Array();
    4. //good
    5. const item = {};
    6. const items = [];
  3. 不允许使用关键字作为变量和键值

    1. // bad
    2. const default = 0;
    3. const superman = {
    4. default: { clark: 'kent' },
    5. private: true
    6. };
    7. //good
    8. const defaults = 0;
    9. const superman = {
    10. defaults: { clark: 'kent' },
    11. hidden: true,
    12. };
  4. 向数组添加元素时,使用push函数,不允许使用直接赋值的方式

    1. // bad
    2. let items = [];
    3. items[items.length] = 'zhinanzhen';
    4. //good
    5. let items = [];
    6. items.push('zhinanzhen');
  5. 使用解构赋值的方式复制数组

    1. // bad
    2. const len = items.length;
    3. const itemsCopy = [];
    4. let i;
    5. for (i = 0; i < len; i++) {
    6. itemsCopy[i] = items[i];
    7. }
    8. //good
    9. const itemsCopy = [...items];
  6. 对象转数组使用数组的from方法


    1. const foo = document.querySelectorAll('.foo');
    2. const nodes = Array.from(foo);
  7. 推荐使用解构存取和多属性对象

    1. // bad
    2. function getFullName(user) {
    3. const firstName = user.firstName;
    4. const lastName = user.lastName;
    5. return `${firstName} ${lastName}`;
    6. }
    7. //good
    8. function getFullName(obj) {
    9. const { firstName, lastName } = obj;
    10. return `${firstName} ${lastName}`;
    11. }
    12. //best
    13. function getFullName({ firstName, lastName }) {
    14. return `${firstName} ${lastName}`;
    15. }
  8. 数组推荐使用解构赋值


    1. const arr = [1, 2, 3, 4];
    2. const [first, second] = arr;
  9. 字符串使用单引号(eslint推荐使用一致的单引号或者双引号)


    1. // bad
    2. const name = "zhinanzhen";
    3. // good
    4. const name = 'zhinanzhen';
  10. ***推荐使用模版字符串


    1. function sayHi(name) {
    2. return `How are you, ${name}?`;
    3. }
  11. 推荐使用函数声明代替函数表达式(var声明的函数表达式,函数的声明会被提升,但是函数体不会;函数声明的名称和函数体都会被提升)


    1. // bad
    2. const foo = function () {
    3. //doSomething();
    4. };
    5. // good
    6. function foo() {
    7. const foo = function () {
    8. //doSomething();
    9. };
    10. }
  12. 不允许在if,while中声明一个函数


    1. // bad
    2. let a = 2;
    3. if (a > 0){
    4. function foo(){
    5. //doSomething()
    6. }
    7. }
  13. 不允许把参数声明为arguments(eslint: 不允许函数的参数重名),且使用rest语法代替arguments


    1. // bad
    2. function nope(name, options, arguments) {
    3. // ...stuff...
    4. }
    5. // bad
    6. function concatenateAll() {
    7. const args = Array.prototype.slice.call(arguments);
    8. return args.join('');
    9. }
    10. // good
    11. function concatenateAll(...args) {
    12. return args.join('');
    13. }
  14. 不允许直接给函数的参数赋值


    1. // bad
    2. var b = 1;
    3. function count(a = b++) {
    4. console.log(a);
    5. }
    6. count(); // 1
    7. count(); // 2
    8. count(3); // 3
    9. count(); // 3
  15. 在必须使用函数表达式或者传递一个匿名函数时,使用箭头函数


    1. // bad
    2. [1, 2, 3].map(function (x) {
    3. return x * x;
    4. });
    5. // good
    6. [1, 2, 3].map((x) => {
    7. return x * x;
    8. });
  16. 推荐使用class,避免直接操作prototype

    1. // bad
    2. function Queue(contents = []) {
    3. this._queue = [...contents];
    4. }
    5. Queue.prototype.pop = function() {
    6. const value = this._queue[0];
    7. this._queue.splice(0, 1);
    8. return value;
    9. }
    10. // good
    11. class Queue {
    12. constructor(contents = []) {
    13. this._queue = [...contents];
    14. }
    15. pop() {
    16. const value = this._queue[0];
    17. this._queue.splice(0, 1);
    18. return value;
    19. }
    20. }
  17. 使用extend继承

    1. // bad
    2. const inherits = require('inherits');
    3. function PeekableQueue(contents) {
    4. Queue.apply(this, contents);
    5. }
    6. inherits(PeekableQueue, Queue);
    7. PeekableQueue.prototype.peek = function() {
    8. return this._queue[0];
    9. }
    10. // good
    11. class PeekableQueue extends Queue {
    12. peek() {
    13. return this._queue[0];
    14. }
    15. }
  18. 不要使用通配符import


    1. // bad
    2. import * as AirbnbStyleGuide from './AirbnbStyleGuide';
    3. // good
    4. import AirbnbStyleGuide from './AirbnbStyleGuide';
  19. 不要在import中直接export


    1. // bad
    2. // filename es6.js
    3. export { es6 as default } from './airbnbStyleGuide';
    4. // good
    5. // filename es6.js
    6. import { es6 } from './AirbnbStyleGuide';
    7. export default es6;
  20. 使用高阶函数(map(),reduce())替代for-of


    1. const numbers = [1, 2, 3, 4, 5];
    2. // bad
    3. let sum = 0;
    4. for (let num of numbers) {
    5. sum += num;
    6. }
    7. sum === 15;
    8. // good
    9. let sum = 0;
    10. numbers.forEach((num) => sum += num);
    11. sum === 15;
    12. // best (use the functional force)
    13. const sum = numbers.reduce((total, num) => total + num, 0);
    14. sum === 15;
  21. 访问对象属性使用‘.’,通过变量访问属性时使用中括号‘[]’


    1. const luke = {
    2. jedi: true,
    3. age: 28,
    4. };
    5. // bad
    6. const isJedi = luke['jedi'];
    7. // good
    8. const isJedi = luke.jedi;
    9. function getProp(prop) {
    10. return luke[prop];
    11. }
    12. const isJedi = getProp('jedi');
  22. 将const和let分组


    1. // bad
    2. let i, len, dragonball,
    3. items = getItems(),
    4. goSportsTeam = true;
    5. // bad
    6. let i;
    7. const items = getItems();
    8. let dragonball;
    9. const goSportsTeam = true;
    10. let len;
    11. // good
    12. const goSportsTeam = true;
    13. const items = getItems();
    14. let dragonball;
    15. let i;
    16. let length;
  23. 优先使用 === 和 !== 而不是 == 和 !=.

  24. 条件表达式里面的值使用简写的方式

    1. // bad
    2. if (name !== '') {
    3. // ...stuff...
    4. }
    5. // good
    6. if (name) {
    7. // ...stuff...
    8. }
    9. // bad
    10. if (collection.length > 0) {
    11. // ...stuff...
    12. }
    13. // good
    14. if (collection.length) {
    15. // ...stuff...
    16. }

    注意:条件表达式例如 if 语句通过抽象方法 ToBoolean 强制计算它们的表达式并且总是遵守下面的规则:

    1. 对象:true
    2. Undefined:false
    3. Null :false
    4. 布尔值 :布尔的值
    5. 数字 :+0、-0、或 NaN 算为 false, 否则为 true
    6. 字符串:如果是空字符串 '' 为 false,否则为 true
    7. 数组:true(包括空数组 [] )
  25. 多行代码使用大括号包裹


    1. // bad
    2. if (test)
    3. return false;
    4. function() { return false; }
    5. // good
    6. if (test) return false;
    7. if (test) {
    8. return false;
    9. }
    10. function() {
    11. return false;
    12. }
  26. 如果通过 if 和 else 使用多行代码块,把 else 放在 if 代码块关闭括号的同一行。


    1. // bad
    2. if (test) {
    3. thing1();
    4. thing2();
    5. }
    6. else {
    7. thing3();
    8. }
    9. // good
    10. if (test) {
    11. thing1();
    12. thing2();
    13. } else {
    14. thing3();
    15. }
  27. *** 使用 /** ... */ 作为多行注释,包含描述、指定所有参数和返回值的类型和值。


    1. // bad
    2. // make() returns a new element
    3. // based on the passed in tag name
    4. //
    5. // @param {String} tag
    6. // @return {Element} element
    7. function make(tag) {
    8. // ...stuff...
    9. return element;
    10. }
    11. // good
    12. /**
    13. * make() returns a new element
    14. * based on the passed in tag name
    15. *
    16. * @param {String} tag
    17. * @return {Element} element
    18. */
    19. function make(tag) {
    20. // ...stuff...
    21. return element;
    22. }
  28. 使用 // 作为单行注释。在评论对象上面另起一行使用单行注释。在注释前插入空行。


    1. // bad
    2. const active = true; // is current tab
    3. // good
    4. // is current tab
    5. const active = true;
    6. // bad
    7. function getType() {
    8. console.log('fetching type...');
    9. // set the default type to 'no type'
    10. const type = this._type || 'no type';
    11. return type;
    12. }
    13. // good
    14. function getType() {
    15. console.log('fetching type...');
    16. // set the default type to 'no type'
    17. const type = this._type || 'no type';
    18. return type;
    19. }
  29. 给注释增加 FIXME 或 TODO 的前缀可以帮助其他开发者快速了解这是一个需要复查的问题,或是给需要实现的功能提供一个解决方式

    1. // good
    2. class Calculator {
    3. constructor() {
    4. // FIXME: shouldn't use a global here
    5. total = 0;
    6. }
    7. }
    8. class Calculator {
    9. constructor() {
    10. // TODO: total should be configurable by an options param
    11. this.total = 0;
    12. }
    13. }
  30. 使用两个空格作为缩进;

  31. 大括号前面使用一个空格;

  32. 在控制语句(if、while 等)的小括号前放一个空格;在函数调用及声明中,不在函数的参数列表前加空格


    1. // bad
    2. if(isJedi) {
    3. fight ();
    4. }
    5. // good
    6. if (isJedi) {
    7. fight();
    8. }
    9. // bad
    10. function fight () {
    11. console.log ('Swooosh!');
    12. }
    13. // good
    14. function fight() {
    15. console.log('Swooosh!');
    16. }
  33. 使用空格把运算符隔开;


    1. // bad
    2. const x=y+5;
    3. // good
    4. const x = y + 5;
  34. 在文件末尾,块儿末,新语句前插入空行插入一个空行


    1. // bad
    2. if (foo) {
    3. return bar;
    4. }
    5. return baz;
    6. // good
    7. if (foo) {
    8. return bar;
    9. }
    10. return baz;
    11. // bad
    12. const obj = {
    13. foo() {
    14. },
    15. bar() {
    16. },
    17. };
    18. return obj;
    19. // good
    20. const obj = {
    21. foo() {
    22. },
    23. bar() {
    24. },
    25. };
    26. return obj;
  35. 不要在行首插入逗号


    1. // bad
    2. const story = [
    3. once
    4. , upon
    5. , aTime
    6. ];
    7. // good
    8. const story = [
    9. once,
    10. upon,
    11. aTime,
    12. ];
  36. 给对象定义属性的时候增加结尾的逗号


    1. // bad
    2. const story = [
    3. firstName: 'Dana',
    4. lastName: 'Scully',
    5. ];
    6. // good
    7. const story = [
    8. firstName: 'Dana',
    9. lastName: 'Scully',
    10. ];
  37. 分号的使用


    1. // bad
    2. (function() {
    3. const name = 'Skywalker'
    4. return name
    5. })()
    6. // good
    7. (() => {
    8. const name = 'Skywalker';
    9. return name;
    10. })();
    11. // good (防止函数在两个 IIFE 合并时被当成一个参数)
    12. ;(() => {
    13. const name = 'Skywalker';
    14. return name;
    15. })();
  38. 在语句开始前执行类型转换


    1. // => this.reviewScore = 9;
    2. // bad
    3. const totalScore = this.reviewScore + '';
    4. // good
    5. const totalScore = String(this.reviewScore);
  39. 对数字使用 parseInt 转换,并带上类型转换的基数

    1. const inputValue = '4';
    2. // bad
    3. const val = new Number(inputValue);
    4. // bad
    5. const val = +inputValue;
    6. // bad
    7. const val = inputValue >> 0;
    8. // bad
    9. const val = parseInt(inputValue);
    10. // good
    11. const val = Number(inputValue);
    12. // good
    13. const val = parseInt(inputValue, 10);
  40. 在使用长方法链时进行缩进。使用前面的点 . 强调这是方法调用而不是新语句

    1. // bad
    2. $('#items').find('.selected').highlight().end().find('.open').updateCount();
    3. // bad
    4. $('#items').
    5. find('.selected').
    6. highlight().
    7. end().
    8. find('.open').
    9. updateCount();
    10. // good
    11. $('#items')
    12. .find('.selected')
    13. .highlight()
    14. .end()
    15. .find('.open')
    16. .updateCount();
  41. 使用具有意义的命名方式


    1. // bad
    2. function q() {
    3. // ...stuff...
    4. }
    5. // good
    6. function query() {
    7. // ..stuff..
    8. }
  42. 使用驼峰命名对象和函数


    1. // bad
    2. const OBJEcttsssss = {};
    3. const this_is_my_object = {};
    4. function c() {}
    5. // good
    6. const thisIsMyObject = {};
    7. function thisIsMyFunction() {}
  43. 使用帕斯卡式(首字母大写)命名构造函数或类


    1. // bad
    2. function user(options) {
    3. this.name = options.name;
    4. }
    5. const bad = new user({
    6. name: 'nope',
    7. });
    8. // good
    9. class User {
    10. constructor(options) {
    11. this.name = options.name;
    12. }
    13. }
    14. const good = new User({
    15. name: 'yup',
    16. });
  44. 不要使用下划线 _ 结尾或开头来命名属性和方法


    1. // bad
    2. this.__firstName__ = 'Panda';
    3. this.firstName_ = 'Panda';
    4. this._firstName = 'Panda';
    5. // good
    6. this.firstName = 'Panda';
  45. 不要保存this的引用,使用箭头函数或者bind保存


    1. // bad
    2. function foo() {
    3. const self = this;
    4. return function() {
    5. console.log(self);
    6. };
    7. }
    8. // bad
    9. function foo() {
    10. const that = this;
    11. return function() {
    12. console.log(that);
    13. };
    14. }
    15. // good
    16. function foo() {
    17. return () => {
    18. console.log(this);
    19. };
    20. }
  46. 如果文件只有一个类,那文件名必须与类名保持一致


    1. // file contents
    2. class CheckBox {
    3. // ...
    4. }
    5. export default CheckBox;
    6. // in some other file
    7. // bad
    8. import CheckBox from './checkBox';
    9. // bad
    10. import CheckBox from './check_box';
    11. // good
    12. import CheckBox from './CheckBox';
  47. 存取函数时使用getVal() 和 setVal('hello')

    1. // bad
    2. echeng.age();
    3. // good
    4. echeng.getAge();
    5. // bad
    6. echeng.age(25);
    7. // good
    8. echeng.setAge(25);
  48. 属性是布尔值的时候使用isVal() 或 hasVal()


    1. // bad
    2. if (!dragon.age()) {
    3. return false;
    4. }
    5. // good
    6. if (!dragon.hasAge()) {
    7. return false;
    8. }
  49. set()和get()要保持一致


    1. set(key, val) {
    2. this[key] = val;
    3. }
    4. get(key) {
    5. return this[key];
    6. }
  50. 缓存jQuery查询


    1. // bad
    2. function setSidebar() {
    3. $('.sidebar').hide();
    4. // ...stuff...
    5. $('.sidebar').css({
    6. 'background-color': 'pink'
    7. });
    8. }
    9. // good
    10. function setSidebar() {
    11. const $sidebar = $('.sidebar');
    12. $sidebar.hide();
    13. // ...stuff...
    14. $sidebar.css({
    15. 'background-color': 'pink'
    16. });
    17. }
  51. 使用 $ 作为存储 jQuery 对象的变量名前缀


    1. // bad
    2. const sidebar = $('.sidebar');
    3. // good
    4. const $sidebar = $('.sidebar');
  52. 对DOM查询使用层叠 $('.sidebar ul') 或 父元素 > 子元素 $('.sidebar > ul')的方式

  53. 对有作用域的jQuery对象查询使用 find

    1. // bad
    2. $('ul', '.sidebar').hide();
    3. // bad
    4. $('.sidebar').find('ul').hide();
    5. // good
    6. $('.sidebar ul').hide();
    7. // good
    8. $('.sidebar > ul').hide();
    9. // good
    10. $sidebar.find('ul').hide();
    1. 原文首创,转载请注明出处。

eslint推荐编码规范和airbnb推荐编码规范的更多相关文章

  1. 【转】Airbnb React编码规范

    Airbnb的编码规范是在业界非常流行的一套规范,而且它一直都在进化,推出最新技术的规范 原文:https://zhuanlan.zhihu.com/p/20616464 用更合理的方式书写React ...

  2. 前端编码规范(2)—— HTML 规范

    HTML 规范 文档类型 推荐使用 HTML5 的文档类型申明: <!DOCTYPE html>. (建议使用 text/html 格式的 HTML.避免使用 XHTML.XHTML 以及 ...

  3. 前端编码风格规范(3)—— JavaScript 规范

    JavaScript 规范 全局命名空间污染与 IIFE 总是将代码包裹成一个 IIFE(Immediately-Invoked Function Expression),用以创建独立隔绝的定义域.这 ...

  4. 【PHP开发规范】老生常谈的编码开发规范你懂多少?

    [PHP开发规范]老生常谈的编码开发规范你懂多少? 这几天看了一下阿里技术发布的一套Java开发规范<阿里巴巴Java开发手册>,里面写了阿里内部的Java开发规范标准,写的很好.这套Ja ...

  5. 前端编码规范(2)HTML 规范

    文档类型 推荐使用 HTML5 的文档类型申明: <!DOCTYPE html> (建议使用 text/html 格式的 HTML.避免使用 XHTML.XHTML 以及它的属性,比如 a ...

  6. 坑爹的对GBK编码的字符进行url编码

    url编码又叫百分号编码 现在的url编码十分混乱,都没有按照新标准来 对汉字都按照不同的编码后再进行url编码 2005年1月发布的RFC 3986,强制所有新的URI必须对未保留字符不加以百分号编 ...

  7. 【JAVA编码专题】JAVA字符编码系列一:Unicode,GBK,GB2312,UTF-8概念基础

    这两天抽时间又总结/整理了一下各种编码的实际编码方式,和在Java应用中的使用情况,在这里记录下来以便日后参考. 为了构成一个完整的对文字编码的认识和深入把握,以便处理在Java开发过程中遇到的各种问 ...

  8. 从原理上搞定编码(二)-- Web编码

    周末宅在家里睡完觉就吃饭,吃完饭接着睡觉,这日子过的实在是没劲啊.明明还有计划中的事情没有做, 为什么就是不想去做呢,这样的生活持续下去,必然会成为一个彻头彻尾的loser.上一篇写的 初识编码 ,这 ...

  9. UTF-8和GBK编码之间的区别(页面编码、数据库编码区别)以及在实际项目中的应用

    第一节:UTF-8和GBK编码概述 UTF-8 (8-bit Unicode Transformation Format) 是一种针对Unicode的可变长度字符编码,又称万国码,它包含全世界所有国家 ...

随机推荐

  1. chromeDriver下载地址

    http://chromedriver.storage.googleapis.com/index.html

  2. Package pdftex.def Error: PDF mode expected, but DVI mode detected!

    本系列文章由 @yhl_leo 出品,转载请注明出处. 文章链接: http://blog.csdn.net/yhl_leo/article/details/51646781 在如下使用LaTeX编译 ...

  3. hdu_1020_Encoding_201310172120

    Encoding Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total S ...

  4. [luogu1156]垃圾陷阱_动态规划_背包dp

    垃圾陷阱 luogu-1156 题目大意:Holsteins在距离地面D英尺的地方,FJ间隔时间ti会往下扔第i个垃圾.Holsteins对待每一个垃圾都会选择吃掉或者垫高.Holsteins有10个 ...

  5. [poj3070]Fibonacci_矩乘_快速幂

    Fibonacci poj-3070 题目大意:求Fibonacci第n项. 注释:模数为10000,$1\le n \le 10^9$. 想法:矩阵题,用例题6的想法,我们构造矩阵 $\begin{ ...

  6. GDB 调试 PHP文件

    http://www.bo56.com/%E5%9C%A82016%E7%9A%84phpcon%E5%A4%A7%E4%BC%9A%E4%B8%8A%E7%9A%84%E5%88%86%E4%BA% ...

  7. shell中eval命令

    原文:http://www.cnblogs.com/xdzone/archive/2011/03/15/1984971.html 语法:eval cmdLine eval会对后面的cmdLine进行两 ...

  8. c/c++ 数据结构之位图(bitmap)具体解释

    1.  概述 位图(bitmap)是一种很经常使用的结构,在索引.数据压缩等方面有广泛应用. 本文介绍了位图的实现方法及其应用场景. 2. 位图实现 2014728101320" alt=& ...

  9. 【面试】【Spring常见问题总结】【07】

    [常见面试问题总结文件夹>>>] 61.Spring IoC容器的依赖有两层含义: Bean依赖容器:也就是说Bean要依赖于容器,这里的依赖是指容器负责创建Bean并管理Bean的 ...

  10. CSS学习(十四)-CSS颜色之中的一个

    一.理论: 1.RGB色彩模式  a.CMYK色彩模式  b.索引色彩模式 (主要用于web) c.灰度模式  d.双色调模式 2.opacity: a.alphavalue:透明度 b.inheri ...