js中类型判断

JS判断数据类型

js基本类型有 Undefined、Null、Boolean、Number和String,Object(由名值对集合)

typeof判断类型

   var nullValue = null,boolValue = true,nmValue=12,strValue = 'test';
   var objValue={x:y},arrayValue = [1,23,3],
   functionValue = function(){
       console.info('function')
   };
   typeof nullValue == 'object';//true
   typeof boolValue == 'boolean';//true
   typeof nmValue == 'number';//true
   typeof strValue  == 'string';//true
   typeof objValue== 'object';//true
   typeof unValue== 'undefined';//true
   typeof arrayValue == 'object';//true
   typeof functionValue == 'function';//true
   typeof NaN//"number"
   /*
   *typeof 只能准确判断Undefined、Boolean、Number和String类型和function
   *对Null,Object,Array测试其值为'object'
   **/

instanceof判断

instanceof 判断已知对象,主要用于判断Array,object等

  [1,2]  instanceof Array;//true 数组
  new Date() instanceof Date;//Data
  var Obj = function(){}
  Obj.prototype.info = function(){
    console.info(Array.prototype.slice.apply(argument,[1]))
  }
  var testObj = new Obj();
  testObj instanceof Obj;//true  自定义对象
  var fucObj = function(){};
  fucObj  instanceof Function;//true 函数判断
  /*
  *instanceof 适合对象判断
  **/

constructor判断

适用于对象的判断

   false.constructor === Boolean;//true
   'test'.constructor === String;//true
   [1,23].constructor === Array;//true  
   var obj = {x:1}
   obj .constructor === Object;//true
  var funtest = function(){}
  funtest .constructor === Function;//true
  new Date().constructor  === Date;//true
  //对于继承
  var A = function(){};
  var B = function(){};
  A.prototype = new B();
  var a = new A();
  a.constructor === B;//true
  a.constructor === A;//false
  /*
  *此处对于instanceof 能胜任判断
  **/

Object.prototype.toString.apply()判断

  "[Object Array]" === Object.prototype.toString.apply([]);//true
  "[object Object]"=== Object.prototype.toString.apply({});//true
  "[object String]" === Object.prototype.toString.apply('123');//true
  "[object Number]" === Object.prototype.toString.apply(123);//true
  "[object Boolean]" === Object.prototype.toString.apply(false);//true
  "[object Date]" === Object.prototype.toString.apply(new Date());//
  "[object Null]" === Object.prototype.toString.apply(null);//true
  "[object Undefined]" ===  Object.prototype.toString.apply(undefined);//true
posted @ 2015-11-03 23:36  伯济  阅读(482)  评论(0编辑  收藏  举报