javascript类型判断方法

时间:2023-03-09 09:26:07
javascript类型判断方法

判断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]