JS学习笔记(四)之调试
-
使用控制台检查变量值
console.log();
- 使用 type of 检查变量的类型
console.log(typeof ""); // 输出 "string" console.log(typeof 0); // 输出 "number" console.log(typeof []); // 输出 "object" console.log(typeof {}); // 输出 "object"
- 捕获拼错的变量名和函数名,未闭合的括号、方括号、大括号和引号等问题
- 单引号和双引号的混合用法
可以使用反斜杠 () 转义字符来转义字符串中的引号// 这些是正确的: const grouchoContraction = "I've had a perfectly wonderful evening, but this wasn't it."; const quoteInString = "Groucho Marx once said 'Quote me as saying I was mis-quoted.'"; // 这是不正确的: const uhOhGroucho = 'I've had a perfectly wonderful evening, but this wasn't it.';
// 一种引号的正确使用方式: const allSameQuotes = 'I\'ve had a perfectly wonderful evening, but this wasn\'t it.';
- 使用赋值运算符而不是相等运算符
let x = 1; let y = 2; if (x = y) { // 除了 "falsy" 值以外 y 为任意值时这个代码块都将执行 } else { // 按本例用意这个代码块应该执行(但其实不会)。 }
- 函数调用后缺少的左括号和右括号
function myFunction() { return "You rock!"; } let varOne = myFunction; // 将函数赋值给变量 let varTwo = myFunction(); // 将函数返回值 "You rock!"赋给变量
- 调用函数时,捕获以错误顺序传递的参数
- 使用索引的时候出现的错误
let alphabet = "abcdefghijklmnopqrstuvwxyz"; let len = alphabet.length; for (let i = 0; i <= len; i++) { // 在最后多了一次循环 console.log(alphabet[i]); } for (let j = 1; j < len; j++) { // 循环少了一次,漏掉了索引 0 处的字符 console.log(alphabet[j]); } for (let k = 0; k < len; k++) { // 不多不少,这才是正确的 console.log(alphabet[k]); }
-
重新初始化循环中的变量时要小心
创建一个具有m行和n列“零”的二维数组。
function zeroArray(m, n) { let newArray = []; for (let i = 0; i < m; i++) { let row = []; /* <----- row has been declared inside the outer loop. Now a new row will be initialised during each iteration of the outer loop allowing for the desired matrix. */ for (let j = 0; j < n; j++) { row.push(0); } newArray.push(row); } return newArray; } let matrix = zeroArray(3, 2); console.log(matrix);
-
使用有效的终止条件防止无限循环
有一个无限循环的例子——它没有终止条件来摆脱loopy()内的while循环。不要调用这个函数!
function loopy() { while(true) { console.log("Hello, world!"); } }