当前位置: 首页 > Web前端 > HTML

判断对象的类型

时间:2023-03-28 10:50:58 HTML

判断变量的类型1.通过typeof判断写法:typeofvariableortypeof(variable)typeof只能判断五个值:number,string,boolean,function,undefined//例子var一=1;varisF=true;console.log(typeofa)//numberconsole.log(typeofisF)//boolean2.使用instanceof判断用法:objectinstanceofconstructor判断对象原型链上是否有constructor.prototype//例子vararr=[1,2,3];console.log(arrinstaceofArray);//true3,从constructor属性来看,构造函数上有constructor属性,创建的实例会继承这个属性,可以通过这个属性类型获取变量。注意:null和undefined没有这个属性//examplevarstr='abc';console.log(str.constructor)//[函数字符串]4.借用Object的toString方法,通过Object.prototype.toString.call(obj),结果是字符串,字符串是数组,第一项数组是对象,第二项是变量类型。//例子vararr=[1,2,3];console.log(Object.prototype.toString.call(arr))//[对象数组]