📖
JavaScript - 網站程式設計
  • JavaScript - 網站程式設計
  • 1. 簡介
    • 1.1 講者簡介
    • 1.2 課程簡介
    • 1.3 開發工具簡介
  • 2. JS 在網頁上的基本觀念
    • 2.1 變數宣告
    • 2.2 資料型態
    • 2.3 基礎節點操控
    • 2.4 套用方式
  • 3. 瀏覽器物件模型 (BOM)
    • 3.1 Window
    • 3.2 Location
    • 3.3 內建彈出視窗
  • 4. 文件物件模型 (DOM)
    • 4.1 DOM 簡介
    • 4.2 取得節點、內容、屬性
    • 4.3 節點查找(Traversing)
    • 4.4 更新節點
    • 4.5 新增節點
    • 4.6 刪除節點、屬性
    • 4.7 操控 class 屬性
    • 4.8 練習
  • 5. 事件 (Events)
    • 5.1 事件(Event)簡介
    • 5.2 事件物件(Event Object)
    • 5.3 window 及 document 事件
    • 5.4 滑鼠相關事件
    • 5.5 鍵盤相關事件
    • 5.6 scroll 事件
    • 5.7 表單事件及停止元素預設行為
    • 5.8 動態事件綁定
    • 5.9 練習
  • 6. 表單 (Form)
    • 6.1 取得表單資料
    • 6.2 設定表單資料
    • 6.3 練習
  • 7. 儲存機制(Storage)
    • 7.1 Cookies
    • 7.2 localStorage
  • 8. ECMAScript (ES)
    • 8.1 Template String
    • 8.2 Arrow Function
    • 8.3 Spread and Rest Operator
    • 8.4 物件屬性簡寫
    • 8.5 解構賦值
  • 9. 作業
  • 10. 參考資料
Powered by GitBook
On this page
  • 變數的資料型態
  • 字串(String)
  • 數值(Number)
  • 布靈(Boolean)
  • 物件(Object)
  • 陣列(Array)
  • 未定義(undefined)
  • 空(null)
  • 函式(function)
  • 總結
  1. 2. JS 在網頁上的基本觀念

2.2 資料型態

可以直接在 console 中來測試觀察。

變數的資料型態

請直接在 console 中,輸入以下各範例來觀察變數的資料型態。

可以用 typeof 來檢測變數的資料類型,包含以下:

字串(String)

用雙引號或單引號括起來的,會被視為字串:

var my_job = "web designer";
typeof my_job; // 回傳 "string"

數值(Number)

數值的部份,例如 1、1.5 等:

var a = 1;
var b = "1";
typeof a; // 回傳 "number"
typeof b; // 回傳 "string"

布靈(Boolean)

true 、 false 就是布靈值:

var c = true;
var d = false;
typeof c; // 回傳 "boolean"
typeof d; // 回傳 "boolean"

物件(Object)

以 左右大括號 括起:

var e = {b: 1};
typeof e; // 回傳 "object"

陣列(Array)

以 左右中括號 括起:

var f = [1, 2]; // 這種較常用
var g = new Array("a", "b", "c"); // 這是另一種寫法

typeof f; // 回傳 "object"
typeof g; // 回傳 "object"

JavaScript 總會遇到一些奇怪的行為,像這裡是回傳 "object",而不是 "array",也是為人所詬病之處,但這樣的錯誤已經很多年,如果把它修正的話,會造成很多網站會出錯,所以就乾脆不修正。

未定義(undefined)

特殊關鍵字:

var h = undefined;
typeof h; // 回傳 "undefined"

空(null)

特殊關鍵字:

var i = null;
typeof i; // 回傳 "object"

同陣列,這也是為人所詬病之處。

函式(function)

var j = function(){
  return "a";
};

typeof j; // 回傳 "function"

也可以寫以下這樣,「有名稱的函式」:

function add(){
  return "add";
}

typeof add; // 回傳 "function"

總結

以上算起來,利用 typeof 回傳的資料類型,總共六個:

  • "string"

  • "number"

  • "boolean"

  • "object"

  • "undefined"

  • "function"

Previous2.1 變數宣告Next2.3 基礎節點操控

Last updated 1 month ago