代码质量
包括语法、注释、规范。
调试
有 3 种方式来暂停一个脚本:
- 断点。
- debugger 语句。
- error(开发者工具打开+控制台开启)。
语法
如下是一些需要遵守的代码规范(建议)。
花括号
if (n < 0) {
alert(`Power ${n} is not supported`);
}
行的长度
没有人喜欢读一长串代码,最好将代码分割一下。
// 回勾引号 ` 允许将字符串拆分为多行
let str = `
ECMA International's TC39 is a group of JavaScript developers,
implementers, academics, and more, collaborating with the community
to maintain and evolve the definition of JavaScript.
`;
// 对于 if 语句 :
if (
id === 123 &&
moonPhase === 'Waning Gibbous' &&
zodiacSign === 'Libra'
) {
letTheSorceryBegin();
}
一行代码的最大长度应该在团队层面上达成一致。通常是 80 或 120 个字符。
缩进
有两种类型的缩进:
- 水平方向上的缩进:2 或 4 个空格。
- 垂直方向上的缩进:用于将代码拆分成逻辑块的空行。
插入一个额外的空行有助于使代码更具可读性。 写代码时,不应该出现连续超过 9 行都没有被垂直分割的代码。
分号
每一个语句后面都应该有一个分号。即使它可以被跳过。