javascript中對變量類型的判斷方法

使用typeof檢測

  • var num = 123; "number"
  • var str = 'abcdef'; "string"
  • var bool = true; "boolean"
  • var arr = [1, 2, 3, 4]; "object"
  • var json = {name:'wenzi', age:25}; "object"
  • var func = function(){ console.log('this is function'); } "function"
  • var und = undefined; "undefined"
  • var nul = null; "object"
  • var date = new Date(); "object"
  • var reg = /[1]{5,20}$/; "object"
  • var error= new Error(); "object"

檢測:typeof num;返回"number"json

使用instanceof檢測

  • 要求開發者明確地確認對象爲某特定類型: num instanceof number 返回false
  • num, str和bool沒有檢測出他的類型

使用constructor檢測

constructor原本是原型對象上的屬性,指向構造函數。數組

  • Tom.constructor==Person,
  • num.constructor==Number,
  • str.constructor==String,
  • bool.constructor==Boolean,
  • arr.constructor==Array,
  • json.constructor==Object,
  • func.constructor==Function,
  • date.constructor==Date,
  • reg.constructor==RegExp,
  • error.constructor==Error 除了undefined和null,其餘類型的變量均能使用constructor判斷出類型,不過使用constructor也不是保險的,由於constructor屬性是能夠被修改的,會致使檢測出的結果不正確

使用Object.prototype.toString.call檢測

如:Object.prototype.toString.call(num) 返回'[object Number]'函數

  • 能夠使用Object.prototype.toString.call(arr)=="object Array"來檢測變量arr是否是數組

  1. a-zA-Z ↩︎this

相關文章
相關標籤/搜索