js中判断数据类型的4中方法

注意: js中数据类型有7种(number, boolean, string, null, undefined, object, Symbol(es6新增))

原始数据类型: number, string, boolean

引用数据类型(合成类型): object

特殊类型: null ,undefined

 

一 最常用方法,基本类型 typeof

   typeof 运算符的最终结果有6种

   "number" ->  typeof 123 ; typeof NaN

   "string"    ->   typeof "123"

   "boolean" ->  typeof  true

   "function"  ->  function f() {}; typeof f

   "object"    ->  typeof {}; typeof [];typeof new Date(); typeof null; typeof window  //缺点: 不能细分对象,数组,时间对象

   "undefined" -> typeof undefined; typeof 未定义变量

二 判断对象类型 instanceof

    判断是否为某个构造函数或者类的实例

    ([2]) instanceof Array  -> true

    (new Date()) instanceof Date -> true

    (function(){}) instanceof Function  -> true

    ({}) instanceof Object  -> true

    null,undefined 使用该运算法的时候,返回值永远是 false

三 判断对象类型 constructor

    constructor属性的作用是,可以得知某个实例对象,到底是哪一个构造函数产生的。

    因为js规定P.prototype.constructor === P

 

      (new Date()).constructor === Date  -> true

    ([2]).constructor === Array -> true

    (function(){}).constructor ===  Function  -> true

    ({}).constructor === Object  -> true

 instanceof 和 constructor 两者区别:

 

   function A(){};
   function B(){};
   A.prototype = new B(); //A继承自B
   var aobj = new A();
   console.log(aobj.constructor === B)  -> true
   console.log(aobj.constructor === A)  -> false
   console.log(aobj instanceof A)          -> true
   console.log(aobj instanceof B)          -> true

 class A{};
   class B{};
   A.prototype = new B(); //A继承自B
   var obj = new A();
   console.log(obj.constructor === B)  -> false
   console.log(obj.constructor === A)  -> true
   console.log(obj instanceof A)          -> true
   console.log(obj instanceof B)          -> false

四. 通用方法   

   Object.prototype.toString() 默认返回类型字符串。所有的值都继承该方法。

   但是数组、字符串、函数、Date 对象都又定义了属于自己的toString方法,覆盖了继承的Object.prototype的toString()方法。

   所以为了可以判断所有的类型,统一使用Object.prototype.toString.call(value),来判断数据类型。

   call方法是用于改变this的指向,value就是方法运行时的实例对象,如果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]

 

 *************判断一个变量是否是对象的方法*************

function isObject(value) {
  return   value === Object(value)
}
// 注意,原始类型的值通过Object()函数之后,会变成对应的包装对象;
// 对象(数组,对象,函数)等于本身

**************************************************** 

 

 

 

    

    

    

   

 

转载于:https://www.cnblogs.com/lyraLee/p/10469772.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值