翻譯: Português, Spanish, 繁體中文, 簡體中文javascript
standard 規則列表,太多沒必要閱讀。html
瞭解 standard
的最好方式是安裝它,而後寫代碼嘗試。java
縮進使用兩個空格。git
eslint: indent
github
function hello (name) { console.log('hi', name) }
字符串使用單引號,除非是爲了不轉義。web
eslint: quotes
正則表達式
console.log('hello there') $("<div class='box'>")
無未使用的變量。api
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')
始終處理函數的 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') // ✓ 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: no-cond-assign
// ✓ ok while ((m = text.match(expr))) { // ... } // ✗ avoid while (m = text.match(expr)) { // ... }
單行語句塊的內側要有空格。
eslint: block-spacing
function foo () {return true} // ✗ avoid function foo () { return true } // ✓ ok
變量和函數的名字使用 camelCase 格式。
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
文件以空行結尾。
elint: 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: new-parens
function Animal () {} var dog = new Animal // ✗ avoid var dog = new Animal() // ✓ ok
對象若定義了 setter 則必須定義相應的 getter。
eslint: accessor-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 } }
使用對象字面量,不使用對象構造函數。
eslint: no-array-constructor
var nums = new Array(1, 2, 3) // ✗ avoid var nums = [1, 2, 3] // ✓ ok
不使用 arguments.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) }
不要給 class 賦值。
eslint: no-class-assign
class Dog {} Dog = 'Fido' // ✗ avoid
不要修改由 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-control-regex
var pattern = /\x1f/ // ✗ avoid var pattern = /\x20/ // ✓ ok
不使用 debugger
語句。
eslint: no-debugger
function sum (a, b) { debugger // ✗ avoid return a + b }
不要對變量使用 delete
操做符。
eslint: no-delete-var
var name delete name // ✗ avoid
函數定義無重複參數。
eslint: no-dupe-args
function sum (a, b, a) { // ✗ avoid // ... } function sum (a, b, c) { // ✓ ok // ... }
class 定義無重複成員。
eslint: no-dupe-class-members
class Dog { bark () {} bark () {} // ✗ avoid }
對象字面量無重複鍵名。
eslint: 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 }
每一個模塊只使用一個 import 語句。
eslint: no-duplicate-imports
import { myFunc1 } from 'module' import { myFunc2 } from 'module' // ✗ avoid import { myFunc1, myFunc2 } from 'module' // ✓ ok
正則表達式無空的字符組。
eslint: no-empty-character-class
const myRegex = /^abc[]/ // ✗ avoid const myRegex = /^abc[a-z]/ // ✓ ok
解構賦值不使用空的 pattern。
eslint: no-empty-pattern
const { a: {} } = foo // ✗ avoid const { a: { b } } = foo // ✓ ok
不使用 eval()
。
eslint: no-eval
eval( "var result = user." + propName ) // ✗ avoid var result = user[propName] // ✓ ok
catch
語句中不要對錯誤對象從新賦值。
eslint: no-ex-assign
try { // ... } catch (e) { e = 'new value' // ✗ avoid } try { // ... } catch (e) { const newVal = 'new value' // ✓ ok }
不要擴展原生對象。
eslint: 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) // ✓ ok
不使用非必要的布爾值轉換。
eslint: no-extra-boolean-cast
const result = true if (!!result) { // ✗ avoid // ... } const result = true if (result) { // ✓ ok // ... }
函數表達式不使用非必要的包裹括號。
eslint: no-extra-parens
const myFunc = (function () { }) // ✗ avoid const myFunc = function () { } // ✓ ok
switch
語句使用 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() }
浮點數應包含整數和小數。
eslint: no-floating-decimal
const discount = .5 // ✗ avoid const discount = 0.5 // ✓ ok
不給聲明過的函數從新賦值。
eslint: no-func-assign
function myFunc () { } myFunc = myOtherFunc // ✗ avoid
不給只讀的全局變量從新賦值。
eslint: no-global-assign
window = {} // ✗ avoid
不使用隱式 eval()
。
eslint: no-implied-eval
setTimeout("alert('Hello world')") // ✗ avoid setTimeout(function () { alert('Hello world') }) // ✓ ok
不在嵌套語句中使用函數聲明。
eslint: no-inner-declarations
if (authenticated) { function setAuthUser () {} // ✗ avoid }
RegExp
構造器不使用非法的正則表達式字符串。
eslint: no-invalid-regexp
RegExp('[a-z') // ✗ avoid RegExp('[a-z]') // ✓ ok
不使用非法空白。
eslint: no-irregular-whitespace
function myFunc () /*<NBSP>*/{} // ✗ avoid
不使用 __iterator__
。
eslint: no-iterator
Foo.prototype.__iterator__ = function () {} // ✗ avoid
label 不使用做用域內變量的名字。
eslint: no-label-var
var score = 100 function game () { score: 50 // ✗ avoid }
不使用 label 語句。
eslint: no-labels
label: while (true) { break label // ✗ avoid }
不使用非必要的嵌套語句塊。
eslint: no-lone-blocks
function myFunc () { { // ✗ avoid myOtherFunc() } } function myFunc () { myOtherFunc() // ✓ ok }
縮進不混用空格和製表符。
eslint: no-mixed-spaces-and-tabs
不使用多個連續空格,縮進除外。
eslint: no-multi-spaces
const id = 1234 // ✗ avoid const id = 1234 // ✓ ok
不使用多行字符串。
eslint: no-multi-str
const message = 'Hello \ world' // ✗ avoid
若是不是賦值則不使用 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
不使用 new require
。
eslint: no-new-require
const myModule = new require('my-module') // ✗ avoid
不使用 Symbol
構造器。
eslint: no-new-symbol
const foo = new Symbol('foo') // ✗ avoid
不使用原始類型的包裝對象。
eslint: no-new-wrappers
const message = new String('hello') // ✗ avoid
全局對象的屬性不用於函數調用。
eslint: no-obj-calls
const math = Math() // ✗ avoid
不使用八進制字面量。
eslint: no-octal
const num = 042 // ✗ avoid const num = '042' // ✓ ok
字符串不使用八進制轉義。
eslint: no-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) // ✓ ok
不重複聲明變量。
eslint: no-redeclare
let name = 'John' let name = 'Jane' // ✗ avoid let name = 'John' name = 'Jane' // ✓ ok
正則表達式中不使用多個連續空白。
eslint: no-regex-spaces
const regexp = /test value/ // ✗ avoid const regexp = /test {3}value/ // ✓ ok const regexp = /test value/ // ✓ ok
在 return 語句中賦值表達式要用括號包裹。
eslint: no-return-assign
function sum (a, b) { return result = a + b // ✗ avoid } function sum (a, b) { return (result = a + b) // ✓ ok }
不將變量賦值給它自身。
eslint: no-self-assign
name = name // ✗ avoid
不將變量跟它自身相比。
esint: no-self-compare
if (score === score) {} // ✗ avoid
不使用逗號操做符。
eslint: no-sequences
if (doSomething(), !!test) {} // ✗ avoid
不修改關鍵字的值。
eslint: no-shadow-restricted-names
let undefined = 'value' // ✗ avoid
不使用稀疏數組(Sparse arrays)。
eslint: no-sparse-arrays
let fruits = ['apple',, 'orange'] // ✗ avoid
不使用製表符。
eslint: no-tabs
普通字符串不要包含模板字符串佔位符。
eslint: no-template-curly-in-string
const message = 'Hello ${name}' // ✗ avoid const message = `Hello ${name}` // ✓ ok
super()
必須在訪問 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') // ✓ ok
行末不要有空白。
eslint: no-trailing-spaces
變量不初始化爲 undefined
。
eslint: no-undef-init
let name = undefined // ✗ avoid let name name = 'value' // ✓ ok
循環語句要更新循環變量。
eslint: no-unmodified-loop-condition
for (let i = 0; i < items.length; j++) {...} // ✗ avoid for (let i = 0; i < items.length; i++) {...} // ✓ ok
簡單的存在賦值不使用三元操做符。
eslint: no-unneeded-ternary
let score = val ? val : 0 // ✗ avoid let score = val || 0 // ✓ ok
return
, 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) // ✗ avoid
無非必要的計算屬性。
eslint: no-useless-computed-key
const user = { ['name']: 'John Doe' } // ✗ avoid const user = { name: 'John Doe' } // ✓ ok
無非必要的構造器。
eslint: no-useless-constructor
class Car { constructor () { // ✗ avoid } }
無非必要的轉義。
eslint: no-useless-escape
let message = 'Hell\o' // ✗ avoid
import, export, 解構賦值不可重命名爲同名變量。
eslint: no-useless-rename
import { config as config } from './config' // ✗ avoid import { config } from './config' // ✓ ok
屬性前面無空白。
eslint: no-whitespace-before-property
user .name // ✗ avoid user.name // ✓ ok12
不使用 with
語句。
eslint: no-with
with (val) {...} // ✗ avoid
對象屬性的換行應一致。
eslint: object-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' } // ✓ ok
語句塊內部首尾無空行。
eslint: padded-blocks
if (user) { // ✗ avoid const name = getName() } if (user) { const name = getName() // ✓ ok }
展開操做符後面無空格。
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: space-unary-ops
typeof!admin // ✗ avoid typeof !admin // ✓ 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
使用 isNaN()
檢查 NaN
。
eslint: use-isnan
if (price === NaN) { } // ✗ avoid if (isNaN(price)) { } // ✓ ok
typeof
必須跟合法的字符串比較。
eslint: valid-typeof
typeof name === 'undefimed' // ✗ avoid typeof name === 'undefined' // ✓ ok
當即調用函數 (IIFEs) 必須用括號包裹。
eslint: wrap-iife
const getName = function () { }() // ✗ avoid const getName = (function () { }()) // ✓ ok const getName = (function () { })() // ✓ ok
yield*
的 *
先後要有一個空格。
eslint: yield-star-spacing
yield* increment() // ✗ avoid yield * increment() // ✓ ok
不使用 Yoda 式條件句比較。
eslint: yoda
if (42 === age) { } // ✗ avoid if (age === 42) { } // ✓ ok
eslint: semi
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」