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

avScript精髓基础进阶(一)数据类型

时间:2023-04-05 18:23:00 HTML5

转载请注明出处链接http://blog.huanghanlian.com/article/5b698e54b8ea642ea9213f49数据类型JavaScript六大数据类型JavaScript一共有六种数据类型,包括五种原始类型,和一种对象类型。JavaScript隐式转换varx='Theanswer'+42;//Theanswer42vary=42+'Theanswer';//42Theanswer中的加号可以理解为字符串的拼接varx="37"-7;//30vary="37"+7;//377这里的减号会理解为减法运算,加号会理解为字符串拼接,相当于判断varx="1.23"==1.23;//truewhenonesideis一个字符串,另一个是数字,它会尝试将字符串转换为数字,然后进行比较vary=0==false;//truevare=null==undefined;//truevarc=newObject()==newObject();//falsevard=[1,2]==[1,2];//false类型不同,try类型转换和比较类型不同,try类型转换和比较:null==undefinedequalnumber==stringtonumber1=="1.0"//trueboolean==?tonumber1==true//trueobject==number|stringtrytoconvertobjecttoprimitivetypenewString('hi')=='hi'//trueOthers:falseisstrictlyequaltoa===b顾名思义,它会先判断两边的类型等号,如果两边类型不同,返回false如果类型相同,相同类型,相同===varh=null===null;//truevarf=undefined===undefined;//truevarg=NaN===NaN;//falsenumber类型,不会等于任何值,包括自己的varl=newObject()===newObject();//falseObjects应该按引用比较,而不是按值比较,因为它们不是完全相同的对象。所以我们定义对象x和y来比较,只有这样它才成立。JavaScript封装对象number、string、boolean的原始类型都有对应的封装类型。vara="string";alert(a.length);//6a.t=3;alert(a.t);//undefinedstring,当试图使用基本类型作为对象时,比如访问length属性时,js会智能地将基本类型转换为对应的封装类型对象。相当于新字符串。当访问完成时,这个临时对象被销毁。所以a.t被赋值为3然后a.t的输出是undefinedjavascript类型检测类型检测有以下类型typeofinstanceofObject.prototype.toStringconstructorduck类型最常见的typeof会返回一个字符串,非常适合判断函数对象和基础typestypeof100==="number"typeoftrue==="boolean"typeoffunction(){}==="function"typeof(undefined))==="undefined"typeof(newObject())==="object"typeof([1,2])==="object"typeof(NaN)==="number"typeof(null)==="object"typeof非常方便判断一些基本类型和函数对象。但是没有办法判断其他对象的类型。比如我要判断一个对象是不是数组,如果我用typeof,它会返回object,这显然不是我想要的。判断对象类型,objinstanceofObject[1,2]instanceofArray===truenewObject()instanceofArray===falsefunctionperson(){};functionstudent(){};student.prototype=newperson();varbosn=newstudent();console.log(bosninstanceofstudent)//truevarone=newperson();console.log(oneinstanceofperson)//trueconsole.log(bosninstanceofperson)//trueObject.prototype.toString**IE6/7/8Object.prototype.toString.apply(null)返回“[objectObject]”**Object.prototype.toString.apply([]);==="[对象数组]";Object.prototype.toString.apply(function(){});==="[对象函数]";Object.prototype.toString.apply(null);===“[objectNull]”Object.prototype。toString.apply(未定义);==="[objectUndefined]"typeof适用于基本类型和函数检测,遇到null时失败。[[Class]]通过{}.toString获取,适用于内置对象和原始类型,遇到null和undefined时失败(IE678等返回[objectObject])。instanceof适用于自定义对象,也可以用来检测原生对象,不同iframe和窗口之间检测会失败。