變數及規則、Undefined、Null、NaN差異?


Posted by RLun on 2022-09-28

變數寫法

  • number
    Infinity正無窮大。
    NaN代表一個計算錯誤。
    var price = 30;
    
  • string
    一串字串組成,必須在引號裡(單引、雙引、反引號皆可)。
    var indexName = ‘Leo’;
    
    反引號可允許跨行。
    var indexName = `List:
    1.Leo
    2.Allen
    3.Jack
    `
    
  • boolean(true/false)
    var isPass = true;
    

變數宣告良好習慣

參考ESLint airbnb 普遍使用的變數宣告風格指南

  • 避免汙染全域的命名空間,請使用const宣告變數
    //不好
    Human = new Creature();
    //良好
    const Human = new Creature();
    
  • 建議一行一個變數,不要再通移行宣告多個變數
    除了增加可讀性之外,除錯時容易知道哪行錯誤。
    //不好
    let name = 'Leo', score = 95, isPass = true;
    //良好
    let name = 'Leo';
    let score = 95;
    let isPass = true;
    
  • 把相同的宣告資料型別分組
    一眼看起來很整齊,增加方便可讀性。
    //不好
    let name = 'Leo';
    const score = getScore();
    let classnum;
    const isForeign = true;
    let id;
    //良好
    const score = getScore();
    const isForeign = true;
    let name = 'Leo';
    let classnum;
    let id;
    
  • 把變數放在合理的位置。
    變數、常數放在需要用到時再宣就好。
    //不好
    let score;
    const isPass = (a,b) =>{
      score = a + b;
    if(score >= 60){
          return true;
      }else{
          return false;   
      }
    }
    //良好
    const isPass = (a,b) =>{
      let score = a + b;
    if(score >= 60){
          return true;
      }else{
          return false;   
      }
    }
    

變數規則

  • 開頭不能以數字為首
  • 不能用 -.
  • 不能使用JavaScript有意義名稱 Ex: true、if、int….專有名詞
  • 區分大小
  • 建議用有語意化,可採用「底線連結」或「駝峰式」命名

Undefined、Null、NaN差異

  • Undefined
    已宣告變數名稱但沒賦予它各種值,「尚未定義」。
    var price;
    console.log(price);  //undefined
    console.log(total);  //defined,沒有宣告變數
    
  • Null
    刻意地給予一個沒有值,又稱「空值」。
    null == undefined  //true
    null === undefined //false
    
  • NaN
    「非數值」,通常是在計算失敗所回傳的數值。
    console.log(typeof NaN); // "number"
    
    得知NaN並不是一個型別,而是number型別。
    判斷型別函數typeof< value >
    typeof undefined //undefined
    typeof null      //object
    typeof NaN       //number
    

#變數 #良好習慣 #規則 #null #undefined #NaN #javascript #Web







Related Posts

[25] 強制轉型 - 隱含的強制轉型、Addition Operator、Strings <> Numbers

[25] 強制轉型 - 隱含的強制轉型、Addition Operator、Strings <> Numbers

[第九週]  PHP 與 MySQL 的互動:讀取資料

[第九週] PHP 與 MySQL 的互動:讀取資料

〈 C++學習日記 #2〉再談指標 Pointer (Part.2)

〈 C++學習日記 #2〉再談指標 Pointer (Part.2)


Comments