JavaScript Standard Style

本文列举的是常见规范

原文地址,点击这里

细则

  • 使用两个空格 进行缩进

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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,302评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,563评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,433评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,628评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,467评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,354评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,777评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,419评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,725评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,768评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,543评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,387评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,794评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,032评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,305评论 1 252
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,741评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,946评论 2 336

推荐阅读更多精彩内容