Skip to content

代码格式

  • 使用二个空格进行缩进。

    eslint: indent

    js
    function hello(name) {
      console.log('hi', name);
    }
  • 除需要转义的情况外,字符串统一使用单引号

    eslint: quotes

    js
    console.log('hello there');
    $("<div class='box'>");
    const testDiv = '<div id="test"></div>';
  • 代码需要加分号

    eslint: semi

    js
    if (condition) { ... };   // ✓ ok
    if(condition) { ... }    // ✗ avoid
  • 括号

    下列关键字后必须有大括号(即使代码块的内容只有一行):if, else, for, while, do, switch, try, catch, finally, with。

    js
    // ✓ ok
    if (condition) {
      doSomething();
    }
    // ✗ avoid
    if (condition) {
      doSomething();
    }
  • undefined 判断

    永远不要直接使用 undefined 进行变量判断;使用 typeof 和字符串 'undefined' 对变量进行判断。

    js
    // ✓ ok
    if (typeof person === 'undefined') {
      ...
    }
    // ✗ avoid
    // person 为 null 也是 true
    if (person == undefined) {
      ...
    }
  • 慎用 console.log

    console.log 大量使用会有性能问题,所以在非 webpack 项目中谨慎使用 log 功能

  • 空行

    以下几种情况需要空行:

    • 变量声明后(当变量声明在代码块的最后一行时,则无需空行)
    • 注释前(当注释在代码块的第一行时,则无需空行)
    • 代码块后(在函数调用、数组、对象中则无需空行)
    • 文件最后保留一个空行