按照 Standard官方建议,项目开启本规范验证后,将不再需要 ESlint及 Prettier进行代码格式验证,可减少各种配置文件(方案一)。但为了避免冲突、做好兼容,并保留一定调整余地,本规范中有 方案二作为灵活集成方案:
【资料图】
Standard版)在开启本规范验证前,删除与 ESlint及 Prettier两个插件相关的依赖注册及项目根目录的相应配置文件;【方案二】(以下称 ESLint版)保留 ESlint及 Prettier两个插件的依赖及配置,在 ESlint中引入eslint-config-standard配置,并来将个人配置包装在上层。- 方案说明standard规范制定的目的,就是让大家都不再花时间浪费在无谓的代码风格之争上面。因此:方案一将全盘接受 standard标准,并且不支持更改;方案二则支持在将本规范集成到 ESlint之中,并支持自定义个人配置;本规范建议:方案一仅做记录,不支持项目应用;各框架选择方案二实行。本规范强烈建议:为保证团队规范的一致性,各项目【不要】自行覆盖与本规范相关的要求。- 其他说明对于开启本规范的项目,将会在项目 package.json中,直接按照 方案一/二预先配置好相关操作,前后端开发人员直接使用即可。
下面全局安装方案,仅提供前端开发人员参考,方便在任何地方进行规范检测。
全局安装示例
npm i -g standard # standard基础包npm i -g eslint-plugin-html@3.2.2 #用于检测html或vue文件<script></script>中的代码,必须是3x版本npm i -g snazzy #用户对输出错误进行美化(非强制安装)【方案一】Standard版(删除ESlint版方案)- 安装依赖仅做记录,暂不支持项目应用,前期使用请暂时参考
方案二
项目安装
# 进入项目目录npm i -D standard # standard基础包npm i -D eslint-plugin-html@3.2.2 #用于检测html或vue文件<script></script>中的代码,必须是3x版本npm i -D husky@next #安装husky git 钩子,用于强制git提交时进行检查npm i -D snazzy #用户对输出错误进行美化(非强制安装)- 配置安装好依赖资源后,更改项目的 package.json 文件
// package.json{ "scripts": { "standard": "standard ${file} | snazzy", "fix": "standard ${file} --fix" }, "standard": { // 声明各种挂载到window上使用的全局变量,避免弹出变量undefined问题 "globals": [ "localStorage", "screen", "sessionStorage", "alert", "location", "Notification" ] }, "husky": { "hooks": { "pre-commit": "standard \"src/**/*.{js,vue}\" | snazzy", } }}- 使用略(暂不支持项目应用)【方案二】ESlitnt版 (集成ESlint版方案)- 安装依赖项目安装
# 进入项目目录"babel-eslint": "10.1.0","eslint": "^7.0.0","eslint-config-standard": "^14.1.1","eslint-plugin-vue": "^7.0.0","lint-staged": "8.1.5","husky": "1.3.1",npm- 配置安装好依赖资源后,更改项目的 package.json文件
// package.json{ "scripts": { "lint": "eslint --ext .js,.vue src", "lintfix": "eslint --fix --ext .js,.vue src", }, "lint-staged": { "src/**/*.{js,vue}": [ "eslint --fix", "git add" ] }, "husky": { "hooks": { "pre-commit": "lint-staged" } }}更改项目的 .eslintrc.js文件
rules中调整部分框架关闭的规则,为【试行版】,请勿私自调整。具体忽略的 rules,请以各端公共框架的 .eslintrc.js为准// .eslintrc.jsmodule.exports = { root: true, parserOptions: { parser: "babel-eslint", sourceType: "module", }, env: { browser: true, node: true, es6: true, }, // extends: ["plugin:vue/recommended", "eslint:recommended"], extends: ["plugin:vue/essential", "standard"], rules: { // 【试行版】禁用规则,请勿自行调整。 eqeqeq: ["off"], "no-template-curly-in-string": ["off"], "vue/script-setup-uses-vars": ["off"], "vue/no-mutating-props": ["off"], "no-new": ["off"], },};- 使用可使用命令行操作,进行规则的检测和修复
npm run lint # 检测项目语法规范npm run lintfix # 修复不合规语法除此之外,还可根据编译器配置自动检测和修复(下文 FAQ以常见的 vscode和 webstorm为例介绍)
(略)
二、如何隐藏某类警告?JavaScript Standard 代码规范底层使用的是 ESLint。所以如果想隐藏某些警告,方法和使用 ESLint 时一样。隐藏代码示例// 对某一行禁用所有规则: file = "I know what I am doing" // eslint-disable-line // 或者,只禁用 "no-use-before-define" 这条规则: file = "I know what I am doing" // eslint-disable-line no-use-before-define // 或者,对多行禁用 "no-use-before-define" 这一规则: /* eslint-disable no-use-before-define */ console.log("offending code goes here...") console.log("offending code goes here...") console.log("offending code goes here...") /* eslint-enable no-use-before-define */ // 禁用某个文件的所有校验,直接在文件头部添加: /* eslint-disable camelcase */三、如何排除某些文件?ESLint版直接按照 ESLint配置即可Standard版可以在 package.json中增加 standard.ignore属性配置:"standard": { "ignore": [ "**/out/", "tmp.js", "......" ] }四、使用全局变量,如何避免 "variable is not defined" 的错误提示?经过测试,ESLint版不会出现这个问题。Standard版可以在 package.json中增加 standard.globals属性配置:"standard": { "globals": [ "alert", "location", "……" ] }五、如果我不同意某条规则,可以改吗?说一下整体原则:Standard规范的目的就是让大家都不再花时间浪费在无谓的代码风格之争上面。因此,原生 Standard版不支持任何自定义规则。ESLint版由于是在ESLint中引入了 eslint-config-standard插件来实现规范约束,因为可以在 .eslintrc.js文件中覆盖 rules,但为了框架规范的一致性,除框架层面统一调整规范,各项目请勿私自调整。具体 ESLint版忽略的 rules,请以各端公共框架的 .eslintrc.js为准※ 其他FAQ篇幅有限,其他未尽事宜,请直接查阅Standard官网:JavaScript Standard Style
使用两个空格进行缩进。
eslint: indent
function hello (name) { console.log("hi", name)}除需要转义的情况外,字符串统一使用单引号。
eslint: quotes
console.log("hello there")$("")不要定义未使用的变量。
eslint: no-unused-vars
function myFunction () { var result = something() // ✗ avoid}
关键字后面加空格。
eslint: keyword-spacing
if (condition) { ... } // ✓ okif(condition) { ... } // ✗ avoid
函数声明时括号与函数名间加空格。
eslint:space-before-function-paren
function name (arg) { ... } // ✓ okfunction name(arg) { ... } // ✗ avoidrun(function () { ... }) // ✓ okrun(function() { ... }) // ✗ avoid
始终使用===替代 ==。例外: obj == null可以用来检查 null || undefined。
eslint: eqeqeq
if (name === "John") // ✓ okif (name == "John") // ✗ avoid
if (name !== "John") // ✓ okif (name != "John") // ✗ avoid
字符串拼接操作符 (Infix operators)之间要留空格。
eslint:space-infix-ops
// ✓ okvar x = 2var message = "hello, " + name + "!"
// ✗ avoidvar x=2var message = "hello, "+name+"!"
逗号后面加空格。
eslint:comma-spacing
// ✓ okvar list = [1, 2, 3, 4]function greet (name, options) { ... }
// ✗ avoidvar list = [1,2,3,4]function greet (name,options) { ... }
else 关键字要与花括号保持在同一行。
eslint: brace-style
// ✓ okif (condition) { // ...} else { // ...}
// ✗ avoidif (condition){ // ...}else{ // ...}
多行 if 语句的的括号不能省。
eslint: curly
// ✓ okif (options.quiet !== true) console.log("done")
// ✓ okif (options.quiet !== true) { console.log("done")}
// ✗ avoidif (options.quiet !== true)console.log("done")
不要丢掉异常处理中 err参数。
eslint:handle-callback-err
// ✓ okrun(function (err) { if (err) throw err window.alert("done")})
// ✗ avoidrun(function (err) { window.alert("done")})
使用浏览器全局变量时加上window.前缀。document、console和 navigator除外。
eslint: no-undef
window.alert("hi") // ✓ ok
不允许有连续多行空行。
eslint: no-multiple-empty-lines
// ✓ okvar value = "hello world"console.log(value)
// ✗ avoidvar value = "hello world"console.log(value)
对于三元运算符?和 :与他们所负责的代码处于同一行
eslint: operator-linebreak
// ✓ okvar location = env.development ? "localhost" : "www.api.com"// ✓ okvar location = env.development ? "localhost" : "www.api.com"// ✗ avoidvar location = env.development ? "localhost" : "www.api.com"
每个 var 关键字单独声明一个变量。
eslint: one-var
// ✓ okvar silent = truevar verbose = true// ✗ avoidvar silent = true, verbose = true// ✗ avoidvar silent = true, verbose = true
条件语句中赋值语句使用括号包起来。这样使得代码更加清晰可读,而不会认为是将条件判断语句的全等号(===)错写成了等号(=)。
eslint:no-cond-assign
// ✓ okwhile ((m = text.match(expr))) { // ...}// ✗ avoidwhile (m = text.match(expr)) { // ...}
单行代码块两边加空格。
eslint:block-spacing
function foo () {return true} // ✗ avoidfunction foo () { return true } // ✓ ok
对于变量和函数名统一使用驼峰命名法。
eslint: camelcase
function my_function () { } // ✗ avoidfunction myFunction () { } // ✓ okvar my_var = "hello" // ✗ avoidvar 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") // ✗ avoidconsole .log("hello") // ✓ ok
文件末尾留一空行。
eslint: eol-last
函数调用时标识符与括号间不留间隔。
eslint:func-call-spacing
console.log ("hello") // ✗ avoidconsole.log("hello") // ✓ ok
键值对当中冒号与值之间要留空白。
eslint: key-spacing
var obj = { "key" : "value" } // ✗ avoidvar obj = { "key" :"value" } // ✗ avoidvar obj = { "key":"value" } // ✗ avoidvar obj = { "key": "value" } // ✓ ok
构造函数要以大写字母开头。
eslint: new-cap
function animal () {}var dog = new animal() // ✗ avoidfunction Animal () {}var dog = new Animal() // ✓ ok
无参的构造函数调用时要带上括号。
eslint: new-parens
function Animal () {}var dog = new Animal // ✗ avoidvar dog = new Animal() // ✓ ok
对象中定义了存值器,一定要对应的定义取值器。
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) // ✗ avoidvar 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)}
避免对类名重新赋值。
eslint:no-class-assign
class Dog {}Dog = "Fido" // ✗ avoid
避免修改使用 const声明的变量。
eslint:no-const-assign
const score = 100score = 125 // ✗ avoid
避免使用常量作为条件表达式的条件(循环语句除外)。
eslint:no-constant-condition
if (false) { // ✗ avoid // ...}if (x === 0) { // ✓ ok // ...}while (true) { // ✓ ok // ...}
正则中不要使用控制符。
eslint:no-control-regex
var pattern = /\x1f/ // ✗ avoidvar pattern = /\x20/ // ✓ ok
不要使用 debugger。
eslint: no-debugger
function sum (a, b) { debugger // ✗ avoid return a + b}
不要对变量使用 delete操作。
eslint:no-delete-var
var namedelete name // ✗ avoid
不要定义冗余的函数参数。
eslint: no-dupe-args
function sum (a, b, a) { // ✗ avoid // ...}function sum (a, b, c) { // ✓ ok // ...}
类中不要定义冗余的属性。
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}
同一模块有多个导入时一次性写完。
eslint:no-duplicate-imports
import { myFunc1 } from "module"import { myFunc2 } from "module" // ✗ avoidimport { myFunc1, myFunc2 } from "module" // ✓ ok
正则中不要使用空字符。
eslint:no-empty-character-class
const myRegex = /^abc[]/ // ✗ avoidconst myRegex = /^abc[a-z]/ // ✓ ok
不要解构空值。
eslint:no-empty-pattern
const { a: {} } = foo // ✗ avoidconst { a: { b } } = foo // ✓ ok
不要使用 eval()。
eslint: no-eval
eval( "var result = user." + propName ) // ✗ avoidvar 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
避免多余的函数上下文绑定。
eslint:no-extra-bind
const name = function () { getName()}.bind(user) // ✗ avoidconst name = function () { this.getName()}.bind(user) // ✓ ok
避免不必要的布尔转换。
eslint:no-extra-boolean-cast
const result = trueif (!!result) { // ✗ avoid // ...}const result = trueif (result) { // ✓ ok // ...}
不要使用多余的括号包裹函数。
eslint:no-extra-parens
const myFunc = (function () { }) // ✗ avoidconst myFunc = function () { } // ✓ ok
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()}
不要省去小数点前面的0。
eslint:no-floating-decimal
const discount = .5 // ✗ avoidconst 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")") // ✗ avoidsetTimeout(function () { alert("Hello world") }) // ✓ ok
嵌套的代码块中禁止再定义函数。
eslint:no-inner-declarations
if (authenticated) { function setAuthUser () {} // ✗ avoid}
不要向 RegExp构造器传入非法的正则表达式。
eslint:no-invalid-regexp
RegExp("[a-z") // ✗ avoidRegExp("[a-z]") // ✓ ok
不要使用非法的空白符。
eslint:no-irregular-whitespace
function myFunc () /**/{} // ✗ avoid
禁止使用 __iterator__。
eslint: no-iterator
Foo.prototype.__iterator__ = function () {} // ✗ avoid
外部变量不要与对象属性重名。
eslint: no-label-var
var score = 100function game () { score: while (true) { // ✗ avoid score -= 10 if (score > 0) continue score break }}
不要使用标签语句。
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 // ✗ avoidconst id = 1234 // ✓ ok
不要使用多行字符串。
eslint: no-multi-str
const message = "Hello \ world" // ✗ avoid
new创建对象实例后需要赋值给变量。
eslint: no-new
new Character() // ✗ avoidconst 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 octal = 042 // ✗ avoidconst decimal = 34 // ✓ okconst octalString = "042" // ✓ ok
字符串字面量中也不要使用八进制转义字符。
eslint:no-octal-escape
const copyright = "Copyright \251" // ✗ avoid
使用 __dirname和 __filename时尽量避免使用字符串拼接。
eslint:no-path-concat
const pathToFile = __dirname + "/app.js" // ✗ avoidconst pathToFile = path.join(__dirname, "app.js") // ✓ ok
使用 getPrototypeOf来替代 __proto__。
eslint: no-proto
const foo = obj.__proto__ // ✗ avoidconst foo = Object.getPrototypeOf(obj) // ✓ ok
不要重复声明变量。
eslint: no-redeclare
let name = "John"let name = "Jane" // ✗ avoidlet name = "John"name = "Jane" // ✓ ok
正则中避免使用多个空格。
eslint:no-regex-spaces
const regexp = /test value/ // ✗ avoidconst regexp = /test {3}value/ // ✓ okconst 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
正确使用 ES6 中的字符串模板。
eslint:no-template-curly-in-string
const message = "Hello ${name}" // ✗ avoidconst message = `Hello ${name}` // ✓ ok
使用 this前请确保 super()已调用。
eslint:no-this-before-super
class Dog extends Animal { constructor () { this.legs = 4 // ✗ avoid super() }}
用 throw抛错时,抛出 Error对象而不是字符串。
eslint:no-throw-literal
throw "error" // ✗ avoidthrow new Error("error") // ✓ ok
行末不留空格。
eslint:no-trailing-spaces
不要使用 undefined来初始化变量。
eslint:no-undef-init
let name = undefined // ✗ avoidlet namename = "value" // ✓ ok
循环语句中注意更新循环变量。
eslint:no-unmodified-loop-condition
for (let i = 0; i < items.length; j++) {...} // ✗ avoidfor (let i = 0; i < items.length; i++) {...} // ✓ ok
如果有更好的实现,尽量不要使用三元表达式。
eslint:no-unneeded-ternary
let score = val ? val : 0 // ✗ avoidlet 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}
关系运算符的左值不要做取反操作。
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" } // ✗ avoidconst 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" // ✗ avoidimport { config } from "./config" // ✓ ok
属性前面不要加空格。
eslint:no-whitespace-before-property
user .name // ✗ avoiduser.name // ✓ ok
禁止使用 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" } // ✓ okconst 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) // ✗ avoidfn(...args) // ✓ ok
遇到分号时空格要后留前不留。
eslint: semi-spacing
for (let i = 0 ;i < items.length ;i++) {...} // ✗ avoidfor (let i = 0; i < items.length; i++) {...} // ✓ ok
代码块首尾留空格。
eslint:space-before-blocks
if (admin){...} // ✗ avoidif (admin) {...} // ✓ ok
圆括号间不留空格。
eslint:space-in-parens
getName( name ) // ✗ avoidgetName(name) // ✓ ok
一元运算符后面跟一个空格。
eslint:space-unary-ops
typeof!admin // ✗ avoidtypeof !admin // ✓ ok
注释首尾留空格。
eslint:spaced-comment
//comment // ✗ avoid// comment // ✓ ok/*comment*/ // ✗ avoid/* comment */ // ✓ ok
模板字符串中变量前后不加空格。
eslint:template-curly-spacing
const message = `Hello, ${ name }` // ✗ avoidconst message = `Hello, ${name}` // ✓ ok
检查 NaN的正确姿势是使用 isNaN()。
eslint: use-isnan
if (price === NaN) { } // ✗ avoidif (isNaN(price)) { } // ✓ ok
用合法的字符串跟 typeof进行比较操作。
eslint: valid-typeof
typeof name === "undefimed" // ✗ avoidtypeof name === "undefined" // ✓ ok
自调用匿名函数 (IIFEs) 使用括号包裹。
eslint: wrap-iife
const getName = function () { }() // ✗ avoidconst getName = (function () { }()) // ✓ okconst getName = (function () { })() // ✓ ok
yield *中的 *前后都要有空格。
eslint:yield-star-spacing
yield* increment() // ✗ avoidyield * increment() // ✓ ok
请书写优雅的条件语句(avoid Yoda conditions)。
eslint: yoda
if (42 === age) { } // ✗ avoidif (age === 42) { } // ✓ ok
关于分号不要使用分号。(参见:1,2,3)
eslint: semi
window.alert("hi") // ✓ okwindow.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)
拓展阅读An Open Letter to JavaScript Leaders RegardingSemicolonsJavaScript Semicolon Insertion -- Everything you need toknow一个值得观看的视频:JavaScript 中的分号多余吗?- YouTube
当前主流的代码压缩方案都是基于词法(AST-based)进行的,所以在处理无分号的代码时完全没有压力(何况JavaScript 中分号本来就不是强制的)。
一段摘抄自"An Open Letter to JavaScript Leaders Regarding Semicolons" 这篇文章的内容:[自动化插入分号的做法]是安全可依赖的,而且其产出的代码能够在所有浏览器里很好地运行。Closure compiler, yuicompressor, packer 还有 jsmin 都能正确地对这样的代码进行压缩处理。并没有任何性能相关的问题。
不得不说,Javascript 社区里的大牛们一直是错误的,并不能教给你最佳实践。真是让人忧伤啊。
我建议先弄清楚 JS是怎样断句的(还有就是哪些地方看起来断了其实并没有),明白了这个后就可以随心写出漂亮的代码了。
一般来说, \n表示语句结束,除非:
该语句有未闭合的括号,数组字面量, 对象字面量 或者其他不能正常结束一条语句的情况(譬如,以 .或 ,结尾)该语句是 --或者 ++,它会将后面的内容进行自增或减)该语句是 for(),while(),do,if()或者 else并且没有 {下一行以 [,(,+,*,/,-,,,.或者其他只会单独出现在两块内容间的二元操作符。第一条很容易理解。即使在 JSLint 中,也允许JSON,构造器的括号中,以及使用 var配合 ,,结尾来声明多个变量等这些情中包含 \n。
第二条有点奇葩。 我还想不出谁会(除了这里用作讨论外)写出 i\n++\nj这样的代码来,不过,顺便说一下,这种写法最后解析的结果是 i; ++j,而不是 i++; j。
第三条也容易理解。 if (x)\ny()等价于 if (x) { y() }。解释器会向下寻找到代码块或一条语句为止。
;是条合法的 JavaScript 语句。所以 if(x);等价于 if(x){},表示"如果 x 为真,什么也不做。",这种写法在循环里面可以看到,就是当条件判断与条件更新是同一个方法的时候。不常见,但也不至于没听说过吧。
第四条就是常见的 "看,说过要加分号!" 的情形。但这些情况可以通过在语句前面加上分号来解决,如果你确定该语句跟前面的没关系的话。举个例子,假如你想这样:
foo();[1,2,3].forEach(bar);
那么完全可以这样来写:
foo();[1,2,3].forEach(bar)
后者的好处是分号比较瞩目,一旦习惯后便再也不会看到以 (和 [开头又不带分号的语句了。
THE END
X 关闭
相关文章
短讯!基于【ESLint+JavaScript Standard Style】标准的VUE/JS/html风格指南
原标题:Guizhou Echo | 这一波,贵州又圈“国际粉”了
家常豆腐最正宗的切法_家常豆腐最正宗的做法
又一网红强势出道!济南福禄考花海盛放,专家:花期长可尽情观赏_最新消息
环球快播:应对沙尘天气 长春环卫5000余人除尘抑尘
- 天天观焦点:广西老虎山山火原因初步查明,2人被刑拘
- 当前热讯:应对空间音频,索尼发布首款开放式监听耳机
- 农村老人丧葬费是多少
- 沈阳三孩家庭每月可领500元育儿补贴 直至孩子3周岁_天天短讯
- 增长34%,这家船企完成民船年度接单任务
- 刘若轩_若轩_最新消息
- 珠宝批发商跨界卖黄金 水贝批发市场租金上涨
- 淄博老板娘为赶高铁小伙1V1烤串 疯狂投喂令网友感动!
- 山水比德中标河北邢台城中村改造,助推城市高质量发展|全球热消息
- “央企进仕佳”洽谈交流会在鹤壁举行
- 【世界播资讯】支教大学生返乡建书屋 帮凉山孩子走出“心中的大山”
- 上海新世界丽笙大酒店有限公司违反传染病防治管理办法被处罚
- 山阳县气象台发布大风蓝色预警【Ⅳ级/一般】【2023-04-12】
- 个人情况介绍范文模板_个人情况介绍范文
- 成都草莓音乐节上男子竖中指挑衅民警,被当场按倒制服|世界微资讯
- 初级会计准考证查询2023
- 罗云熙白鹿cp名“熙米鹿” 被多名商家抢注
- 汉钟精机业绩快报:上半年净利同比增长24.17%
- 泉州市碧莲盛植发医院正规靠谱吗?文亚雄医生植发际线咋样?_通讯
- 大郊亭北街东段:人行道上的违停现象消失了
- 热点!旅游业迎近年来最火热“五一”:多地酒店民宿提前售罄 出境跟团游满员待发
- 银行智慧网点助力老年客户跨越数字鸿沟 当前快讯
- 热议:中材国际(600970):4月11日北向资金减持297.73万股
- 迪奥再次辱华?彩妆广告出现歧视亚裔动作,网友炸了:肯定是故意的
- 国际货币基金组织:全球金融体系的韧性面临多重考验
- 日本防卫省与三菱重工签约,着手开发能从潜艇发射的长射程导弹-当前焦点
- 世界球精选!“琼”尽好物看消博|春暖花开,新消费激发新活力!
- M2已281.46万亿元,暴涨12.7%!大通胀,啥时来临?
- 天天热门:中国中冶一季度新签合同额3258.1亿元,同比增长2.1%
- 护肝不踩“雷”,这4种食物别再吃了!
- 北京市住房和城乡建设委员会2023年市政府工作报告重点任务清单及实事事项一季度工作进展情况
- 孔学堂溪山书会第三十七期:实践与超越里的阳明学-天天快报
- 电动梅赛德斯EQESUV英国价格和规格公布|当前简讯
- 4月11日浙江万方天然橡胶报价平稳
- ETF追踪:昨日ETF净申购5.13亿元 资金加仓创新药ETF
- 世界微速讯:冲刺新能源赛道,乳源这个项目预计年销售收入65亿元
- “未来在此发车” 天天新动态
- 全球今头条!汉缆股份:4月10日融资买入2098.05万元,融资融券余额2.54亿元
- 新股开板提醒:陕西能源打开一字涨停 全球微头条
- 鸿路钢构:4月7日召开业绩说明会,投资者参与
- expectations翻译(greatexpectations)|天天快看
- 热头条丨突发山火!已调派200多人扑救,还有200名消防员在增援途中…请一定平安归来!
- 【天天快播报】王者低配阵容选盘古,儿童阵容抢典韦,高配抢木兰,T0选他
- 枸杞子的作用与功效有哪些_枸杞子的作用 天天热消息
- 环球今热点:医院回应老人长住等候椅:精神不正常 到底是怎么回事?
- new york是哪个州_new york new york 动态焦点
- 环球热点!光华科技(002741.SZ):定增申请获深交所受理
- 抢占新能源赛道,东风Honda带来“e”波惊艳
- 职务侵占如何量刑_环球微资讯
- 看热讯:玲珑轮胎:预计第一季度净利润同比增加318%-339%
- 免票啦!今起神农架正式进入“免票周”时间
- 每日视讯:锦心似玉有小说吗(电视剧锦心似玉原著小说叫什么)
- 今日关注:3月增速最快的竟是这家车企!
- 山西晋城城区禁止露天烧烤:违者没收工具和违法所得,并最高罚款2万|环球快报
- 国家高等教育智慧教育平台上线“创课平台”板块_今日最新
- 续航、售价齐打折 星途追风ET-i背刺老车主 播报
- “乾动2号”深远海养殖平台在福州下水
- 热资讯!全铝合金机箱仅199元 攒机党必看
- 巴尔韦德打人后续!被打球员已报警,黄潜俱乐部声明反对暴力
- 【环球快播报】淘宝手机以旧换新怎么换_手机以旧换新怎么换
- 百花争艳,国潮出街!黄鹤楼举办花朝游园会|全球最新
- 践踏的意思什么意思 天天动态
- 一位杭州顶级牛散直言:如果牛市真的来了,什么样的操作最赚钱?
- 天天热门:桐乡市困难家庭学生助学教育券实施方案 试行_关于桐乡市困难家庭学生助学教育券实施方案 试行简述
- 近百位民族男高音放歌上海,郁钧剑:民族唱法不应边缘化 世界今头条
- 2023年张家界市 “奇峰杯”羽毛球邀请赛开赛
- 千禾味业2022年净利增长55%,仍持续加码产能 | 看财报-环球最新
- 牙列缺损病历书写范文(精选21篇)
- rnds分别是什么档位(rnd挡位分别是什么)_快讯
- here_alone
- 目标销量4200万!特斯拉最便宜的电动车要来了_天天看点
- 今日观点!二十届中央第一轮巡视进驻 第二批21家被巡视单位信访受理方式公布
- 送女神的礼物-焦点热文
- 春风吹暖春经济 | 以花为媒打造消费新场景 助力春日消费“热”起来 环球即时看
- 北美洲上空出现异象,欧洲上空出现“人影”,平行世界出现了? 今日热搜
- 北京银行信用卡还款日是哪天?还款的方式?
- 同济大学校长郑庆华:当前AI技术面临三大挑战 世界今热点
- 中超揭幕战定了!15日晚,北京国安坐镇新工体迎战梅州客家-环球今日讯
- 这些广州新优花卉品种,全球首发_全球速递
- 全国各地区最低工资标准出炉 你的工资不能低于这个数-前沿资讯
- 婚礼父亲礼物都买什么
- 不说谎恋人
- 2023年4月7日云南省钛白粉价格最新行情预测|全球观热点
- 普华永道:跨国企业将继续深耕中国市场
- 快手理想家与七彩云南·古滇名城达成合作 探索文旅+直播卖房新模式-全球快看点
- 世界焦点!ATFX国际:美国3月非农就业报告来袭,市场预期较为悲观
- 地平线4和5哪个值得入手
- 安徽合肥一汽配城门面房火灾致3死
- 每日头条!激动!3万平方米前海山姆旗舰店即将开业!
- 烟台莱山区第二实验幼儿园:开展清明节活动 环球报道
- 医药板块集体反弹!创新药机会来了-全球视讯
- 环球今头条!男生瘦脸的饮食的方法 男生瘦脸的方法有哪些运动
- 【天天快播报】EDG晋级胜者组决赛,Leave赛后感谢UZI,全场鼓掌!
- 华泰证券:看好当前银行修复行情
- ChatGPT板块探底回升 奥飞娱乐涨停
Copyright © 2015-2022 东亚变频网版权所有 备案号:琼ICP备2022009675号-13 联系邮箱:435 227 67 @qq.com