聊一下關於判斷資料型別

pro-xiaoy發表於2018-07-14
  1. 思路

首先整理下js中我們經常碰到的一些資料型別判斷的方法typeofinstanceofconstructorprototype

  1. 區別
  1. typeof操作符返回一個字串,表示未經計算的運算元的型別。選自MDN
console.log(typeof 2)     =====> number
console.log(typeof '1')   =====> string
console.log(typeof false) =====> boolean
console.log(typeof [])    =====> object
console.log(typeof {})    =====> object
console.log(typeof null)  =====> object
console.log(typeof undefined) => undefined
console.log(typeof function(){}) function
console.log(typeof new Date() => object
複製程式碼
  • 關於陣列和物件判斷都是object。他是未經過運算元的型別
  • JavaScript 最初的實現中,JavaScript 中的值是由一個表示型別的標籤和實際資料值表示的。物件的型別標籤是 0。由於 null 代表的是空指標(大多數平臺下值為 0x00),因此,null的型別標籤也成為了 0,typeof null就錯誤的返回了"object"
  1. instance 所述instanceof操作者測試的存在constructor.prototype在object的原型鏈。選自MDN
console.log([] instanceof Array)        ---------------> true
console.log(new Date() instanceof Date) ------------> true
console.log(function(){} instanceof Function) ------------> true
console.log(function(){} instanceof function) ------------> false
複製程式碼
  • 很有意思的一個判斷方法就是[]根據onject和array判斷的時候都為true.{} instanceof Array的答案是false.所以如果有幸自己封裝判斷資料型別這類且方法應該不錯。

3.出自阮一峰老師的javascript教程 toString方法的作用是返回一個物件的字串形式,預設情況下返回型別字串.

Object.prototype.toString.call(value)
數值:返回[object Number]。
字串:返回[object String]。
布林值:返回[object Boolean]。
undefined:返回[object Undefined]。
null:返回[object Null]。
陣列:返回[object Array]。
arguments 物件:返回[object Arguments]。
函式:返回[object Function]。
Error 物件:返回[object Error]。
Date 物件:返回[object Date]。
RegExp 物件:返回[object RegExp]。
其他物件:返回[object Object]。
<!-- 函式的例項 -->
var type = function (o){
  var s = Object.prototype.toString.call(o);
  return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};
複製程式碼

相關文章