JS判断数据类型的几种方法

  1. typeof
    typeof 判断的是基本类型
var num = 1;
var str = "str";
var bool = true;
var func = function () {
}
var obj = {};
var arr = [];
console.log(typeof num);//number
console.log(typeof str);//string
console.log(typeof bool);//boolean
console.log(typeof func);//function
console.log(typeof obj);//object
console.log(typeof arr);//object

nullundefined
console.log(typeof null);//object 这个是js语言的特性导致的
console.log(typeof undefined);//undefined
undefined :是一个表示"无"的原始值或者说表示"缺少值",就是此处应该有一个值,但是还没有定义。当尝试读取时会返回 undefined; 
例如变量被声明了,但没有赋值时,就等于undefined
null : 是一个空值(空对象, 没有任何属性和方法); 
例如作为函数的参数,表示该函数的参数不是对象;
  1. instanceof
    instanceof: A instanceof B ,如果A是B的实例,则返回true,否则返回false。
    instanceof 判断的是对象类型
console.log(1 instanceof Numer) //false
console.log(new Numer(1) instanceof Numer) //true
上面直接自变量赋值方式的定义和new 实例定义严格来说是有区别的,实例创建出来的类才是标准的类
还有就是只要在当前实例的原型链上的,校验出来的结果都为true
console.log([] instanceof Array) // true
console.log([] instanceof Object);  // true
对于特殊类型的nullundefined不能检测
console.log(null instanceof Null) //VM1211:1 Uncaught ReferenceError: Null is not defined
    //at <anonymous>:1:17
    console.log(undefined instanceof undefined ) //VM2058:1 Uncaught TypeError: Right-hand side of 'instanceof' is not an object
    //at <anonymous>:1:12

3.constructor

var aa=[1,2];
console.log(aa.constructor===Array);//true
console.log(aa.constructor===RegExp);//false
console.log((1).constructor===Number);//true

4.Array.prototype.isPrototypeOf(obj)

利用isPrototypeOf()方法,判定Array是不是在obj的原型链中,如果是,则返回true,否则falseArray.prototype.isPrototype([]) //true

5.根据对象的class属性(类属性),跨原型链调用toString()方法
Object.prototype.toString.call()

var num = 1;
var str = "str";
var bool = true;
var func = function () {
}
var obj = {};
var arr = [];

Object.prototype.toString.call(num);//"[object Number]"
Object.prototype.toString.call(str); //"[object String]"
Object.prototype.toString.call(func);//"[object Function]"
Object.prototype.toString.call(bool);//"[object Boolean]"
Object.prototype.toString.call(obj);//"[object Object]"
Object.prototype.toString.call(arr);//"[object Array]"
特殊类型 nullundefined
Object.prototype.toString.call(null) //"[object Null]"
Object.prototype.toString.call(undefined)//"[object Undefined]"
  1. Array.isArray()方法
var arr = [];
console.log(Array.isArray(arr)) //true
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值