翻译自这里。
function hello (name) {
console.log('hi', name)
}
只有在字符串中有单引号时才用双引号。
console.log('hello there')
$("<div class='box'>")
function myFunction () {
var result = something() // ✗ avoid
}
if (condition) { ... } // ✓ ok
if(condition) { ... } // ✗ avoid
JavaScript 中的关键字有 var
, const
, let
, if
, else
, case
, break
, while
, for
, function
, return
等。
function name (arg) { ... } // ✓ ok
function name(arg) { ... } // ✗ avoid
run(function () { ... }) // ✓ ok
run(function() { ... }) // ✗ avoid
例外是可以用 obj == null
来判断对象是 null 或 undefined
if (name === 'John') // ✓ ok
if (name == 'John') // ✗ avoid
if (name !== 'John') // ✓ ok
if (name != 'John') // ✗ avoid
// ✓ ok
var x = 2
var message = 'hello, ' + name + '!'
// ✗ avoid
var x=2
var message = 'hello, '+name+'!'
// ✓ ok
var list = [1, 2, 3, 4]
function greet (name, options) { ... }
// ✗ avoid
var list = [1,2,3,4]
function greet (name,options) { ... }
// ✓ ok
if (condition) {
// ...
} else {
// ...
}
// ✗ avoid
if (condition) {
// ...
}
else {
// ...
}
// ✓ ok
if (options.quiet !== true) console.log('done')
// ✓ ok
if (options.quiet !== true) {
console.log('done')
}
// ✗ avoid
if (options.quiet !== true)
console.log('done')
// ✓ ok
run(function (err) {
if (err) throw err
window.alert('done')
})
// ✗ avoid
run(function (err) {
window.alert('done')
})
例外:document, console 和 navigator。
window.alert('hi') // ✓ ok
alert('hi') // ✗ avoid
// ✓ ok
var value = 'hello world'
console.log(value)
// ✗ avoid
var value = 'hello world'
console.log(value)
// ✓ 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'
// ✓ ok
var silent = true
var verbose = true
// ✗ avoid
var silent = true, verbose = true
// ✗ avoid
var silent = true,
verbose = true
这样做是为了表明这是故意这么做的,而不是因为疏忽
// ✓ ok
while ((m = text.match(expr))) {
// ...
}
// ✗ avoid
while (m = text.match(expr)) {
// ...
}
window.alert('hi') // ✓ ok
window.alert('hi'); // ✗ avoid
// ✓ 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)