天天看點

JS學習筆記(四)之調試

JS學習筆記(四)之調試

  1. 使用控制台檢查變量值

    console.log();

  2. 使用 type of 檢查變量的類型
    console.log(typeof ""); // 輸出 "string"
    console.log(typeof 0); // 輸出 "number"
    console.log(typeof []); // 輸出 "object"
    console.log(typeof {}); // 輸出 "object"
               
  3. 捕獲拼錯的變量名和函數名,未閉合的括号、方括号、大括号和引号等問題
  4. 單引号和雙引号的混合用法
    // 這些是正确的:
    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.';
               
  5. 使用指派運算符而不是相等運算符
    let x = 1;
    let y = 2;
    if (x = y) {
      // 除了 "falsy" 值以外 y 為任意值時這個代碼塊都将執行
    } else {
      // 按本例用意這個代碼塊應該執行(但其實不會)。
    }
    
               
  6. 函數調用後缺少的左括号和右括号
    function myFunction() {
      return "You rock!";
    }
    let varOne = myFunction; // 将函數指派給變量
    let varTwo = myFunction(); // 将函數傳回值 "You rock!"賦給變量
               
  7. 調用函數時,捕獲以錯誤順序傳遞的參數
  8. 使用索引的時候出現的錯誤
    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]);
    }
               
  9. 重新初始化循環中的變量時要小心

    建立一個具有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);
               
  10. 使用有效的終止條件防止無限循環

    有一個無限循環的例子——它沒有終止條件來擺脫loopy()内的while循環。不要調用這個函數!

    function loopy() {
      while(true) {
        console.log("Hello, world!");
      }
    }
               

繼續閱讀