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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值