iT邦幫忙

0

鼠年全馬鐵人挑戰 WEEK 18: JavaScript 變數 型別

  • 分享至 

  • twitterImage
  •  

變數

變數命名規則

  • 變數可以由字母數字下劃線和美元符號($)組成
  • 變數必須以字母開頭
  • 變數也能以 $ 和 _ 符號開頭
  • 變數名稱對大小寫敏感(a 和 A 是不同的變數)
  • 關鍵字保留字都不能做變數名稱使用。

變數運作

在程式執行前,編譯器(compiler)會先由上到下逐行將程式碼轉為電腦可懂的命令,然後再執行編譯後的指令。
所以編譯器(compiler)會先找出所有的變數,但不附值,此時為undefined,在執行時,JavaScript在會處理值

懶人包:先給位置在給值

var a=1;
//拆分步驟
var a ;
console.log(a);//undefined
a=1;
console.log(a);//1

型別

JavaScript型別主要分為基本型別、物件型別

基本型別

  • number 數字,例如:123。
  • string 字串,例如:'Hello World'。
  • boolean 布林,例如:true、false。
  • null
  • undefined
  • symbol

物件型別

  • array 陣列
  • function 函式
    我們可以使用typeof來檢測值的型別是什麼
typeof 'Hello World!'; // 'string'
typeof true; // 'boolean'
typeof 123; // 'number'
typeof null; // 'object'
typeof undefined; // 'undefined'
typeof { name: 'Jason' }; // 'object'
typeof Symbol(); // 'symbol'
typeof function() {}; // 'function'
typeof [1, 2, 3]; // 'object'
typeof NaN; // 'number'
  • null 是基本型別之一,但 typeof null 卻得到 object,而非 null!這是JavaScript的一個bug
  • NaN 表示是無效的數字,但依舊還是數字,因此在資料型別的檢測 typeof NaN 結果就是 number,NaN 與任何數字運算都會得到 NaN,並且 NaN 不大於、不小於也不等於任何數字,包含 NaN 它自己。

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言