纯牛奶645
纯牛奶645
  • 发布:2016-10-24 10:01
  • 更新:2016-10-24 10:01
  • 阅读:1275

js,判断对象的类型,typeof,constructor

分类:Native.js

js判断对象的类型

javascript,判断对象的类型,typeof,constructor

用typeof操作符判断对象类型:(红色文字,是上面一句代码的执行结果)

用对象的构造函数属性(constructor),来判断对象的类型:

区别:

constructor判断对象的类型,会比typeof更精确,constructor能获取一些复杂对象的类型,typeof做不到。

下面有一段程序示例:

代码示例:

<script type="text/javascript" charset="utf-8">

var s='a string';

var arr=[];

var obj=new Object();

if(typeof s=='string'){

console.log( "typeof s=='string' true"); //true

}

//打开浏览器的控制台,可以看到此代码的输出

console.log( 's.constructor==String :'+ (s.constructor==String) );

console.log( 'arr.constructor==Array :'+ (arr.constructor==Array) );

console.log( 'obj.constructor==Object :'+ (obj.constructor==Object) );

//复杂类型的对象,判断其类型

function User(name , age){

this.name=name;

this.age=age;

}

var u=new User();

console.log( 'typeof u :'+typeof u ); //输出object //显然,使用typeof判断复杂类型的对象,就失效了,但使用constructor就可以获取其真实类型

console.log( 'u.constructor.name :'+u.constructor.name );

</script>

0 关注 分享

要回复文章请先登录注册