JavaScript 基礎

JavaScript 有哪些資料型別?該怎麼辨別一個變數的資料型別?

AI 練習作答

JavaScript 有哪些資料型別?

JavaScript 的資料型別分為兩大類:

原始型別(Primitive Types)

共有 7 種:

  • string:字串,例如 'hello'
  • number:數字,例如 423.14
  • bigint:大整數,例如 9007199254740991n
  • boolean:布林值,true / false
  • undefined:變數已宣告但未賦值
  • null:代表「空值」或「無」
  • symbol:唯一且不可變的值(ES6 新增)

物件型別(Object Types)

  • object:包含普通物件、陣列、函式等

如何辨別一個變數的資料型別?

1. typeof 運算子

最常見的方式,但有幾個特殊情況需注意:

typeof 'hello'        // 'string'
typeof 42             // 'number'
typeof true           // 'boolean'
typeof undefined      // 'undefined'
typeof Symbol()       // 'symbol'
typeof 42n            // 'bigint'
typeof {}             // 'object'
typeof []             // 'object'(注意:陣列也是 'object')
typeof null           // 'object'(歷史遺留 bug)
typeof function(){}   // 'function'

2. instanceof 運算子

用來判斷物件是否為某個建構函式的實例:

[] instanceof Array       // true
{} instanceof Object      // true
/regex/ instanceof RegExp // true

3. Object.prototype.toString.call()

最精確的方式,可以區分 null、陣列、函式等:

Object.prototype.toString.call('hello')      // '[object String]'
Object.prototype.toString.call(42)           // '[object Number]'
Object.prototype.toString.call(null)         // '[object Null]'
Object.prototype.toString.call([])           // '[object Array]'
Object.prototype.toString.call({})           // '[object Object]'
Object.prototype.toString.call(function(){}) // '[object Function]'

4. Array.isArray()

專門用來判斷是否為陣列:

Array.isArray([])  // true
Array.isArray({})  // false

總結

方法 適用場景 注意事項
typeof 判斷原始型別 null 和陣列都回傳 'object'
instanceof 判斷物件的實例 無法判斷原始型別
Object.prototype.toString.call() 精確判斷所有型別 較為冗長
Array.isArray() 判斷是否為陣列 最推薦的陣列判斷方式

✦ AI 模擬面試

輸入你的答案,AI 即時分析精準度與改進空間

登入後即可使用 AI 評分