Object.prototype.toString.call() 区分对象类型
在JavaScript中数据类型分为:1.基本类型,2.引用类型
- 基本类型:Undefined,Boolean,String,Number,Null
- 引用类型:Object (Array,Date,RegExp,Function)
var a = ‘hello world‘;var b = [];var c = function(){};
- 1
- 2
- 3
我们用不同的判断类型的方法来判断上面三个变量的类型;(编译工具webStorm,浏览器Chrome)
1.首先:typeof( )
1.console.log(typeof (a)+‘;‘+typeof (b)+‘;‘+typeof (c))输出:string;object;function
- 1
- 2
2.其次:instanceof
console.log(a instanceof Object) ???//falseconsole.log(b instanceof Object) ???//trueconsole.log(c instanceof Object) ???//trueconsole.log(a instanceof Array) ????//falseconsole.log(b instanceof Array) ????//trueconsole.log(c instanceof Array) ????//falseconsole.log(a instanceof Function) ?//falseconsole.log(b instanceof Function) ?//falseconsole.log(c instanceof Function) ?//true
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
从上面两个例题可以看出,typeof(),insctanceof,这两种方法都只能对简单的变量进行判断,如果比较复杂的变量判断时就会有误,不精确;
下面我们介绍Object.prototype.toString.call()方法;
3.Object.prototype.toString.call()
console.log(Object.prototype.toString.call(a))console.log(Object.prototype.toString.call(b))console.log(Object.prototype.toString.call(c))输出:[object String][object Array][object Function]
- 1
- 2
- 3
- 4
- 5
- 6
- 7
可以写个方法传值进入判断:
function isType(obj,type){ ???????if(obj != ‘‘){ ???????????return Object.prototype.toString.call(obj)===‘[object ‘+type+‘]‘ ???????}else{ ???????????alert(‘对象不能为空‘) ???????}} console.log(isType(‘hello world‘,‘String‘)) ?//true ??
JS区分对象类型
原文地址:https://www.cnblogs.com/0828-li/p/9102768.html