DIV CSS 佈局教程網

JavaScript 變數型別判斷:typeof 與 toString 的比較
編輯:關於JavaScript     

型別判斷的常見問題

typeof 可以判斷基本型別,但對陣列、日期、正規表示式等物件容易只回傳 object。此時可借助 Object.prototype.toString.call 取得更精確的內部型別。

function getType(o) {
  var t = typeof o;
  return (t === "object" ? (o === null && "null" || Object.prototype.toString.call(o).slice(8, -1)) : t).toLowerCase();
}

判斷結果示例

  • getType("abc") 回傳 string。
  • getType(true) 回傳 boolean。
  • getType(123) 回傳 number。
  • getType([]) 回傳 array。
  • getType({}) 回傳 object。
  • getType(function() {}) 回傳 function。
  • getType(new Date) 回傳 date。
  • getType(new RegExp) 回傳 regexp。
  • getType(null) 回傳 null。

這種方式比單純使用 typeof 更適合需要區分各種物件型別的情境。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved