美文网首页
JavaScript Standard Style

JavaScript Standard Style

作者: 八杯水多睡觉 | 来源:发表于2017-04-06 14:51 被阅读0次

本文列举的是常见规范

原文地址,点击这里

细则

  • 使用两个空格 进行缩进

eslint: indent

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

eslint: quotes

console.log('hello there')
$("<div class='box'>")
  • 不要留下未使用的变量

eslint: no-unused-vars

function myFunction () {
  var result = something()   // ✗ avoid
}
  • 关键字后面加空格

eslint: keyword-spacing

if (condition) { ... }   // ✓ ok
if(condition) { ... }    // ✗ avoid
  • 函数声明时括号与函数名间加空格

eslint: space-before-function-paren

function name (arg) { ... }   // ✓ ok
function name(arg) { ... }    // ✗ avoid

run(function () { ... })      // ✓ ok
run(function() { ... })       // ✗ avoid
  • 始终使用 === 替代 ==

例外:obj == null 可以用来检查 null || undefined

eslint: eqeqeq

if (name === 'John')   // ✓ ok
if (name == 'John')    // ✗ avoid

if (name !== 'John')   // ✓ ok
if (name != 'John')    // ✗ avoid
  • 字符串拼接操作符(Infix operators)之间要留空格

eslint: space-infix-ops

// ✓ ok
var x = 2
var message = 'hello, ' + name + '!'

// ✗ avoid
var x=2
var message = 'hello, '+name+'!'
  • 逗号后面加空格

eslint: comma-spacing

// ✓ ok
var list = [1, 2, 3, 4]
function greet (name, options) { ... }

// ✗ avoid
var list = [1,2,3,4]
function greet (name,options) { ... }
  • else 关键字要与花括号保持在同一行

eslint: brace-style

// ✓ ok
if (condition) {
  // ...
} else {
  // ...
}

// ✗ avoid
if (condition) {
  // ...
}
else {
  // ...
}
  • 多行if语句的括号不能省

eslint: curly

// ✓ ok
if (options.quiet !== true) console.log('done')

// ✓ ok
if (options.quiet !== true) {
  console.log('done')
}

// ✗ avoid
if (options.quiet !== true)
  console.log('done')
  • 使用浏览器全局变量时加上 window. 前缀

例外: document, console , navigator

eslint: no-undef

window.alert('hi')   // ✓ ok
  • 不允许有连续多行的空行

eslint: no-multiple-empty-lines

// ✓ ok
var value = 'hello world'
console.log(value)
// ✗ avoid
var value = 'hello world'


console.log(value)
  • 对于三元运算符 ?: 与他们所负责的代码处于同一行

eslint: operator-linebreak

// ✓ ok
var location = env.development ? 'localhost' : 'www.api.com'

// ✓ ok
var location = env.development
  ? 'localhost'
  : 'www.api.com'

// ✗ avoid
var location = env.development ?
  'localhost' :
  'www.api.com'
  • 每个 var 关键字单独声明一个变量

eslint: one-var

// ✓ ok
var silent = true
var verbose = true

// ✗ avoid
var silent = true, verbose = true

// ✗ avoid
var silent = true,
    verbose = true
  • 单行代码块两边加空格

eslint: block-spacing

function foo () {return true}    // ✗ avoid
function foo () { return true }  // ✓ ok
  • 对于变量和函数名统一使用驼峰命名法

eslint: camelcase

function my_function () { }    // ✗ avoid
function myFunction () { }     // ✓ ok

var my_var = 'hello'           // ✗ avoid
var myVar = 'hello'            // ✓ ok
  • 不允许有多余的行末逗号

eslint: comma-dangle

var obj = {
  message: 'hello',   // ✗ avoid
}
  • 始终将逗号置于行末

eslint: comma-style

var obj = {
  foo: 'foo'
  ,bar: 'bar'   // ✗ avoid
}

var obj = {
  foo: 'foo',
  bar: 'bar'   // ✓ ok
}
  • 点号操作符须与属性处在同一行

eslint: dot-location

  console.
    log('hello')  // ✗ avoid

  console
    .log('hello') // ✓ ok
  • 文件末尾留一空行

eslint: eol-last

  • 函数调用时标识符与括号间不留间隔

eslint: func-call-spacing

console.log ('hello') // ✗ avoid
console.log('hello')  // ✓ ok
  • 键值对当中冒号与值之间要留空白

eslint: key-spacing

var obj = { 'key' : 'value' }    // ✗ avoid
var obj = { 'key' :'value' }     // ✗ avoid
var obj = { 'key':'value' }      // ✗ avoid
var obj = { 'key': 'value' }     // ✓ ok
  • 构造函数要以大写字母开头

eslint: new-cap

function animal () {}
var dog = new animal()    // ✗ avoid

function Animal () {}
var dog = new Animal()    // ✓ ok
  • 使用数组字面量而不是构造器

eslint: no-array-constructor

var nums = new Array(1, 2, 3)   // ✗ avoid
var nums = [1, 2, 3]            // ✓ ok
  • 避免修改使用 const 声明的变量

eslint: no-const-assign

const score = 100
score = 125       // ✗ avoid
  • 避免使用常量作为条件表达式的条件(循环语句除外)

eslint: no-constant-condition

if (false) {    // ✗ avoid
  // ...
}

if (x === 0) {  // ✓ ok
  // ...
}

while (true) {  // ✓ ok
  // ...
}
  • 同一模块有多个导入时一次性写完

eslint: no-duplicate-imports

import { myFunc1 } from 'module'
import { myFunc2 } from 'module'          // ✗ avoid

import { myFunc1, myFunc2 } from 'module' // ✓ ok
  • 不要扩展原生对象

eslint: no-extend-native

Object.prototype.age = 21     // ✗ avoid
  • switch 一定要使用 break 来将条件分支正常中断

eslint: no-fallthrough

switch (filter) {
  case 1:
    doSomething()    // ✗ avoid
  case 2:
    doSomethingElse()
}

switch (filter) {
  case 1:
    doSomething()
    break           // ✓ ok
  case 2:
    doSomethingElse()
}

switch (filter) {
  case 1:
    doSomething()
    // fallthrough  // ✓ ok
  case 2:
    doSomethingElse()
}
  • 不要对全局只读对象重新赋值

eslint: no-global-assign

window = {}     // ✗ avoid
  • 不要混合使用空格与制表符作为缩进

eslint: no-mixed-spaces-and-tabs

  • 除了缩进,不要使用多个空格

eslint: no-multi-spaces

const id =    1234    // ✗ avoid
const id = 1234       // ✓ ok
  • new 创建对象实例后需要赋值给变量

eslint: no-new

new Character()                     // ✗ avoid
const character = new Character()   // ✓ ok
  • 禁止使用 Function 构造器

eslint: no-new-func

var sum = new Function('a', 'b', 'return a + b')    // ✗ avoid
  • 禁止使用 Object 构造器

eslint: no-new-object

let config = new Object()   // ✗ avoid
  • 使用 __dirname__filename 时尽量避免使用字符串拼接

eslint: no-path-concat

const pathToFile = __dirname + '/app.js'            // ✗ avoid
const pathToFile = path.join(__dirname, 'app.js')   // ✓ ok
  • 不要重复声明变量

eslint: no-redeclare

let name = 'John'
let name = 'Jane'     // ✗ avoid

let name = 'John'
name = 'Jane'         // ✓ ok
  • return 语句中的赋值必需有括号包裹

eslint: no-return-assign

function sum (a, b) {
  return result = a + b     // ✗ avoid
}

function sum (a, b) {
  return (result = a + b)   // ✓ ok
}
  • returnthrowcontinuebreak 这些语句后面的代码都是多余的

eslint: no-unreachable

function doSomething () {
  return true
  console.log('never called')     // ✗ avoid
}
  • 展开运算符与它的表达式间不要留空白

eslint: rest-spread-spacing

fn(... args)    // ✗ avoid
fn(...args)     // ✓ ok
  • 分号前面不留空格,后面留空格

eslint: semi-spacing

for (let i = 0 ;i < items.length ;i++) {...}    // ✗ avoid
for (let i = 0; i < items.length; i++) {...}    // ✓ ok
  • 代码块开始之前留一个空格

eslint: space-before-blocks

if (admin){...}     // ✗ avoid
if (admin) {...}    // ✓ ok
  • 圆括号间不留空格

eslint: space-in-parens

getName( name )     // ✗ avoid
getName(name)       // ✓ ok
  • 注释前后留空格

eslint: spaced-comment

//comment           // ✗ avoid
// comment          // ✓ ok

/*comment*/         // ✗ avoid
/* comment */       // ✓ ok
  • 模板字符串中变量前后不加空格

eslint: template-curly-spacing

const message = `Hello, ${ name }`    // ✗ avoid
const message = `Hello, ${name}`      // ✓ ok
  • 检查 NaN 的正确姿势是使用 isNaN()

eslint: use-isnan

if (price === NaN) { }      // ✗ avoid
if (isNaN(price)) { }       // ✓ ok

关于分号

  • 不要使用分号

eslint: semi

window.alert('hi')   // ✓ ok
window.alert('hi');  // ✗ avoid
  • 不要使用 (, [, or ` 等作为一行的开始。在没有分号的情况下代码压缩后会导致报错,而坚持这一规范则可避免出错。

eslint: no-unexpected-multiline

// ✓ ok
;(function () {
  window.alert('ok')
}())

// ✗ avoid
(function () {
  window.alert('ok')
}())
// ✓ ok
;[1, 2, 3].forEach(bar)

// ✗ avoid
[1, 2, 3].forEach(bar)
// ✓ ok
;`hello`.indexOf('o')

// ✗ avoid
`hello`.indexOf('o')

上面的写法只能说聪明过头了

比如:

;[1, 2, 3].forEach(bar)

建议的写法是:

var nums = [1, 2, 3]
nums.forEach(bar)

相关文章

网友评论

      本文标题:JavaScript Standard Style

      本文链接:https://www.haomeiwen.com/subject/iikqattx.html