代码规范自谈
- 隔几天看一次自己代码;有种和前任分手时感觉 ;一个规范的书写格式是必要性的;也不知道后面会不会被人砍;想起前任离开理由应该就是因为难看吧
- 一个好的规范代码是提升自己自律一部分;也是一种审美 毕竟代码也是我对象 太丑怎么见人
书写规范一些细则:
- 1 使用两个空格进行缩进。
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) { … } // ✓ 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)) {
// …
}
- 单行代码块两边加空格。
e