翻译: Português, Spanish, 繁體中文, 简体中文
standard 规则列表,太多不必阅读。
了解 standard
的最好方式是安装它,然后写代码尝试。
indent
function hello (name) { console.log('hi', name) }quotes
console.log('hello there') $("<div class='box'>")no-unused-vars
function myFunction () { var result = something() // ✗ avoid }keyword-spacing
if (condition) { ... } // ✓ ok if(condition) { ... } // ✗ avoidspace-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') // ✗ avoidspace-infix-ops
// ✓ ok var x = 2 var message = 'hello, ' + name + '!'
// ✗ avoid var x=2 var message = 'hello, '+name+'!'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')err
参数。
eslint: handle-callback-err
// ✓ ok run(function (err) { if (err) throw err window.alert('done') })
// ✗ avoid run(function (err) { window.alert('done') })window.
。
例外: document
, console
和 navigator
。
eslint: no-undef
window.alert('hi') // ✓ okno-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: no-cond-assign
// ✓ ok while ((m = text.match(expr))) { // ... } // ✗ avoid while (m = text.match(expr)) { // ... }block-spacing
function foo () {return true} // ✗ avoid function foo () { return true } // ✓ okcamelcase
function my_function () { } // ✗ avoid function myFunction () { } // ✓ ok var my_var = 'hello' // ✗ avoid var myVar = 'hello' // ✓ okcomma-dangle
var obj = { message: 'hello', // ✗ avoid }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') // ✓ okeol-last
func-call-spacing
console.log ('hello') // ✗ avoid console.log('hello') // ✓ okkey-spacing
var obj = { 'key' : 'value' } // ✗ avoid var obj = { 'key' :'value' } // ✗ avoid var obj = { 'key':'value' } // ✗ avoid var obj = { 'key': 'value' } // ✓ oknew-cap
function animal () {} var dog = new animal() // ✗ avoid function Animal () {} var dog = new Animal() // ✓ oknew-parens
function Animal () {} var dog = new Animal // ✗ avoid var dog = new Animal() // ✓ okaccessor-pairs
var person = { set name (value) { // ✗ avoid this.name = value } } var person = { set name (value) { this.name = value }, get name () { // ✓ ok return this.name } }super
。
eslint: constructor-super
class Dog { constructor () { super() // ✗ avoid } } class Dog extends Mammal { constructor () { super() // ✓ ok } }no-array-constructor
var nums = new Array(1, 2, 3) // ✗ avoid var nums = [1, 2, 3] // ✓ okarguments.callee
和 arguments.caller
。
eslint: no-caller
function foo (n) { if (n <= 0) return arguments.callee(n - 1) // ✗ avoid } function foo (n) { if (n <= 0) return foo(n - 1) }no-class-assign
class Dog {} Dog = 'Fido' // ✗ avoidconst
声明的变量。
eslint: no-const-assign
const score = 100 score = 125 // ✗ avoidno-constant-condition
if (false) { // ✗ avoid // ... } if (x === 0) { // ✓ ok // ... } while (true) { // ✓ ok // ... }no-control-regex
var pattern = /\x1f/ // ✗ avoid var pattern = /\x20/ // ✓ okdebugger
语句。
eslint: no-debugger
function sum (a, b) { debugger // ✗ avoid return a + b }delete
操作符。
eslint: no-delete-var
var name delete name // ✗ avoidno-dupe-args
function sum (a, b, a) { // ✗ avoid // ... } function sum (a, b, c) { // ✓ ok // ... }no-dupe-class-members
class Dog { bark () {} bark () {} // ✗ avoid }no-dupe-keys
var user = { name: 'Jane Doe', name: 'John Doe' // ✗ avoid }switch
语句无重复 case
从句。
eslint: no-duplicate-case
switch (id) { case 1: // ... case 1: // ✗ avoid }no-duplicate-imports
import { myFunc1 } from 'module' import { myFunc2 } from 'module' // ✗ avoid import { myFunc1, myFunc2 } from 'module' // ✓ okno-empty-character-class
const myRegex = /^abc[]/ // ✗ avoid const myRegex = /^abc[a-z]/ // ✓ okno-empty-pattern
const { a: {} } = foo // ✗ avoid const { a: { b } } = foo // ✓ okeval()
。
eslint: no-eval
eval( "var result = user." + propName ) // ✗ avoid var result = user[propName] // ✓ okcatch
语句中不要对错误对象重新赋值。
eslint: no-ex-assign
try { // ... } catch (e) { e = 'new value' // ✗ avoid } try { // ... } catch (e) { const newVal = 'new value' // ✓ ok }no-extend-native
Object.prototype.age = 21 // ✗ avoid.bind()
。
eslint: no-extra-bind
const name = function () { getName() }.bind(user) // ✗ avoid const name = function () { this.getName() }.bind(user) // ✓ okno-extra-boolean-cast
const result = true if (!!result) { // ✗ avoid // ... } const result = true if (result) { // ✓ ok // ... }no-extra-parens
const myFunc = (function () { }) // ✗ avoid const myFunc = function () { } // ✓ okswitch
语句使用 break
,避免运行到下一个 case
。
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() }no-floating-decimal
const discount = .5 // ✗ avoid const discount = 0.5 // ✓ okno-func-assign
function myFunc () { } myFunc = myOtherFunc // ✗ avoidno-global-assign
window = {} // ✗ avoideval()
。
eslint: no-implied-eval
setTimeout("alert('Hello world')") // ✗ avoid setTimeout(function () { alert('Hello world') }) // ✓ okno-inner-declarations
if (authenticated) { function setAuthUser () {} // ✗ avoid }RegExp
构造器不使用非法的正则表达式字符串。
eslint: no-invalid-regexp
RegExp('[a-z') // ✗ avoid RegExp('[a-z]') // ✓ okno-irregular-whitespace
function myFunc () /*<NBSP>*/{} // ✗ avoid__iterator__
。
eslint: no-iterator
Foo.prototype.__iterator__ = function () {} // ✗ avoidno-label-var
var score = 100 function game () { score: 50 // ✗ avoid }no-labels
label: while (true) { break label // ✗ avoid }no-lone-blocks
function myFunc () { { // ✗ avoid myOtherFunc() } } function myFunc () { myOtherFunc() // ✓ ok }no-mixed-spaces-and-tabs
no-multi-spaces
const id = 1234 // ✗ avoid const id = 1234 // ✓ okno-multi-str
const message = 'Hello \ world' // ✗ avoidnew
。
eslint: no-new
new Character() // ✗ avoid const character = new Character() // ✓ okFunction
构造器。
eslint: no-new-func
var sum = new Function('a', 'b', 'return a + b') // ✗ avoidObject
构造器。
eslint: no-new-object
let config = new Object() // ✗ avoidnew require
。
eslint: no-new-require
const myModule = new require('my-module') // ✗ avoidSymbol
构造器。
eslint: no-new-symbol
const foo = new Symbol('foo') // ✗ avoidno-new-wrappers
const message = new String('hello') // ✗ avoidno-obj-calls
const math = Math() // ✗ avoidno-octal
const num = 042 // ✗ avoid const num = '042' // ✓ okno-octal-escape
const copyright = 'Copyright \251' // ✗ avoid__dirname
和 __filename
不用于字符串拼接。
eslint: no-path-concat
const pathToFile = __dirname + '/app.js' // ✗ avoid const pathToFile = path.join(__dirname, 'app.js') // ✓ ok__proto__
,应使用 getPrototypeOf
。
eslint: no-proto
const foo = obj.__proto__ // ✗ avoid const foo = Object.getPrototypeOf(obj) // ✓ okno-redeclare
let name = 'John' let name = 'Jane' // ✗ avoid let name = 'John' name = 'Jane' // ✓ okno-regex-spaces
const regexp = /test value/ // ✗ avoid const regexp = /test {3}value/ // ✓ ok const regexp = /test value/ // ✓ okno-return-assign
function sum (a, b) { return result = a + b // ✗ avoid } function sum (a, b) { return (result = a + b) // ✓ ok }no-self-assign
name = name // ✗ avoidno-self-compare
if (score === score) {} // ✗ avoidno-sequences
if (doSomething(), !!test) {} // ✗ avoidno-shadow-restricted-names
let undefined = 'value' // ✗ avoidno-sparse-arrays
let fruits = ['apple',, 'orange'] // ✗ avoidno-tabs
no-template-curly-in-string
const message = 'Hello ${name}' // ✗ avoid const message = `Hello ${name}` // ✓ oksuper()
必须在访问 this
之前调用。
eslint: no-this-before-super
class Dog extends Animal { constructor () { this.legs = 4 // ✗ avoid super() } }throw
应当抛出一个 Error
对象。
eslint: no-throw-literal
throw 'error' // ✗ avoid throw new Error('error') // ✓ okno-trailing-spaces
undefined
。
eslint: no-undef-init
let name = undefined // ✗ avoid let name name = 'value' // ✓ okno-unmodified-loop-condition
for (let i = 0; i < items.length; j++) {...} // ✗ avoid for (let i = 0; i < items.length; i++) {...} // ✓ okno-unneeded-ternary
let score = val ? val : 0 // ✗ avoid let score = val || 0 // ✓ okreturn
, throw
, continue
, break
语句后面不要有代码。
eslint: no-unreachable
function doSomething () { return true console.log('never called') // ✗ avoid }finally
语句块无流程控制语句。
eslint: no-unsafe-finally
try { // ... } catch (e) { // ... } finally { return 42 // ✗ avoid }in
操作符的左操作数不要使用 !
。
eslint: no-unsafe-negation
if (!key in obj) {} // ✗ avoid.call()
和 .apply()
。
eslint: no-useless-call
sum.call(null, 1, 2, 3) // ✗ avoidno-useless-computed-key
const user = { ['name']: 'John Doe' } // ✗ avoid const user = { name: 'John Doe' } // ✓ okno-useless-constructor
class Car { constructor () { // ✗ avoid } }no-useless-escape
let message = 'Hell\o' // ✗ avoidno-useless-rename
import { config as config } from './config' // ✗ avoid import { config } from './config' // ✓ okno-whitespace-before-property
user .name // ✗ avoid user.name // ✓ okwith
语句。
eslint: no-with
with (val) {...} // ✗ avoidobject-property-newline
const user = { name: 'Jane Doe', age: 30, username: 'jdoe86' // ✗ avoid } const user = { name: 'Jane Doe', age: 30, username: 'jdoe86' } // ✓ ok const user = { name: 'Jane Doe', age: 30, username: 'jdoe86' } // ✓ okpadded-blocks
if (user) { // ✗ avoid const name = getName() } if (user) { const name = getName() // ✓ ok }rest-spread-spacing
fn(... args) // ✗ avoid fn(...args) // ✓ oksemi-spacing
for (let i = 0 ;i < items.length ;i++) {...} // ✗ avoid for (let i = 0; i < items.length; i++) {...} // ✓ okspace-before-blocks
if (admin){...} // ✗ avoid if (admin) {...} // ✓ okspace-in-parens
getName( name ) // ✗ avoid getName(name) // ✓ okspace-unary-ops
typeof!admin // ✗ avoid typeof !admin // ✓ okspaced-comment
//comment // ✗ avoid // comment // ✓ ok /*comment*/ // ✗ avoid /* comment */ // ✓ oktemplate-curly-spacing
const message = `Hello, ${ name }` // ✗ avoid const message = `Hello, ${name}` // ✓ okisNaN()
检查 NaN
。
eslint: use-isnan
if (price === NaN) { } // ✗ avoid if (isNaN(price)) { } // ✓ oktypeof
必须跟合法的字符串比较。
eslint: valid-typeof
typeof name === 'undefimed' // ✗ avoid typeof name === 'undefined' // ✓ okwrap-iife
const getName = function () { }() // ✗ avoid const getName = (function () { }()) // ✓ ok const getName = (function () { })() // ✓ okyield*
的 *
前后要有一个空格。
eslint: yield-star-spacing
yield* increment() // ✗ avoid yield * increment() // ✓ okyoda
if (42 === age) { } // ✗ avoid if (age === 42) { } // ✓ oksemi
window.alert('hi') // ✓ ok window.alert('hi'); // ✗ avoid(
, [
, “` 开始行。这是省略分号时唯一的陷阱。standard 会保护你不落入陷阱。
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)现在所有流行的代码压缩器都是通过 AST 压缩,因此它们在处理没有分号的 JavaScript 代码时没有问题(因为 JavaScript 不是必须使用分号)。
[依赖自动插入分号机制]的代码是非常安全的,是完全合法的 JavaScript 代码,各浏览器都能正确解析;Closure compiler、yuicompressor、packer 及 jsmin 都能正确压缩。没有任何性能影响。
抱歉,我不是向你说教,这个语言的社区领导者在撒谎,并且害怕告诉你真相。真是羞耻。我建议,先了解 JavaScript 语句是如何结束的以及什么情况不会结束,之后你可以写出漂亮的代码。
一般来说,\n
结束语句,除非:
.
或 ,
结束。--
或 ++
,这时它将递减或递增下一个 token。for()
, while()
, do
, if()
, 或 else
,并且没有 <span class="p">{</span>
。[
, (
, +
, *
, /
, -
, ,
, .
,或者是二进制操作符——它们只能出现在一个表达式的两个操作数之间。第一条显而易见。像这些情况:JSON 或括号内有 \n
字符;一个 var
多行声明,每行以 ,
结束,即使是 JSLint 都没问题。
第二条很怪。我从没有看到这种写法 i\n++\nj
。事实上,它被解析为 i; ++j
,而不是 i++; j
。
第三条很好理解。if (x)\ny()
等于 if (x) { y() }
。这个语句直到遇到一个语句块或语句才结束。
;
是一个合法的 JavaScript 语句,所以 if(x);
等于 if(x){}
或 “If x, do nothing.” 。这更多用于循环,这时循环测试同时也是更新函数。不常见,但不是没听过。
第四条通常是那些因循守旧的人提到的情况:“不,你需要分号!”。但是,事实证明,如果你的意思是这些行不是上一行的连续行,那么在这些行之前加上分号非常容易。例如
foo();
[1,2,3].forEach(bar);
可以这么写:
foo()
;[1,2,3].forEach(bar)
这么做的好处是,一旦你习惯了以 (
或 [
开始的行没有分号,你会很容易注意到行首的分号。
结束引用 “An Open Letter to JavaScript Leaders Regarding Semicolons”
由 Ivan Yan 翻译,译文采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议,意见反馈。
更多关于分号的讨论: