1、浏览器调试
F12
如我们所见,暂停脚本有以下三种主要方式:
- 一个断点。 (直接在控制台打)
- 该
debugger声明。(在代码中写 debugger ) - 错误(如果开发工具已打开且按钮 是“开”)。
2、写代码 部分规范
1、 当然可以直接先配置好 vscode prettier 保存时 就格式化代码
-
😠 初学者有时会这样做。this is wrong ,不需要花括号:
if (n < 0) { alert(`Power ${n} is not supported`); } -
😠 拆分为单独的行,不带花括号。永远不要这样做,添加新行时容易出错:
if (n < 0) alert(`do somethings`); -
😏 一行不带大括号 - 可以接受,如果它很短:
if (n < 0) alert(`do somethings`);
2、很长的部分 分成多行展示出来
如下所示:
test(data1,
data2,
data3,
data4,
another
) {
// ...
}
3、有边界 先写出边界条件
- this is wrong
for (let i = 0; i < 6; i++) {
if (code) {
... //
}
}
- this is right
for (let i = 0; i < 6; i++) {
if (!code) continue;
... //
}
4、代码检查 使用 eslint 需要配置 .eslintrc
- 写出简单 容易读 符合 规范的代码 才是 追求
3、写注释
1、好的代码 应该 基本不需要注释 顺着方法 就可能知道在做什么
2、将一个函数内的功能 拆解为多个 函数
有时用函数替换代码片段是有益的,如下所示:(未拆分)
function test(n) {
nextP:
for (let i = 2; i < n; i++) {
for (let j = 2; j < n; j++) {
if (i % j == 0) continue nextP;
}
alert(i);
}
}
- this is right
更好的变体,具有分解功能
isPrime:
function test(n) {
for (let i = 2; i < n; i++) {
if (!nextP(i)) continue;
alert(i);
}
}
function nextP(n) {
for (let i = 2; i < n; i++) {
if (n % i == 0) return false;
}
return true;
}
3、好的注释结构
-
记录函数参数和用法
有一个特殊的语法JSDoc来记录函数:用法、参数、返回值。
例如:
/**
* Returns x raised to the n-th power.
*
* @param {number} x The number to raise.
* @param {number} n The power, must be a natural number.
* @return {number} x raised to the n-th power.
*/
function pow(x, n) {
...
}
4、其他规范
1、命名 不要缩写
list→lst。userAgent→ua。browser→brsr。
2、选择名称时,尽量使用最抽象的词。像obj,data,value,item,elem等
3、命名函数 尽量 以这个函数作用进行命名 小写开头
4、不要 随意使用 下划线命名 会导致 比较迷惑 会在想这个是不是 特殊的用法 lodash 除外 (有个库 _ )
5、代码需要经过测试, 有自动化测试库,后续再说