首页 > 编程语言 > 详细

javascript类型判断方法

时间:2017-05-28 10:42:14      阅读:264      评论:0      收藏:0      [点我收藏+]

判断javascript中的类型,共有四种常用的方法

var a=6;

var b="str";

var c=true;

var arr=[];

typeof 用于基本类型的判断

1.typeof最好用于基本类型的判断,返回类型名(小写)。

例外 typeof null==="object" //true

typeof function(){}==="function" //true

2.typeof返回的是字符串

3.对变量执行typeof操作

得到的不是变量类型,而是变量值的类型,因为JS区别别的语言,变量没有类型,值才有。

instanceof 已知对象类型,进而判断

console.log(arr.constructor===Array);//true

constructor 

console.log(arr.constructor===Array);//true

注意:

constructor在类继承时会出错,instanceof方法不会出现该问题,对象直接继承和间接继承的都会报true

var A=function(){};

var B=function(){};

A.prototype=new B();

var obj=new A();

console.log(obj.constructor===B);//true

console.log(obj.constructor===A)//false

console.log(obj instanceof B)//true

console.log(obj instanceof A)//true

解决方法:obj.constructor = A;手动

 

prototype 最通用方法

Object.prototype.toString.call()

console.log(Object.prototype.toString.call(a))//[object,Number]

javascript类型判断方法

原文:http://www.cnblogs.com/ziqian9206/p/6915158.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!