javascript的两种数据类型转换:1、显式类型转换(又称强制类型转换),主要通过使用JavaScript内置的函数来转换数据;2、隐式类型转换,是指JavaScript根据运算环境自动转换值的类型。
本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
JavaScript 是一种弱类型动态类型语言,变量没有类型限制,可以随时赋予任意值。
var x = y ? 1 : 'a';
上面代码中,变量x到底是数值还是字符串,取决于另一个变量y的值。y为true时,x是一个数值;y为false时,x是一个字符串。这意味着,x的类型没法在编译阶段就知道,必须等到运行时才能知道。
虽然变量的数据类型是不确定的,但是各种运算符对数据类型是有要求的。如果运算符发现,运算子的类型与预期不符,就会自动转换类型。比如,减法运算符预期左右两侧的运算子应该是数值,如果不是,就会自动将它们转为数值。
'4' - '3' // 1
上面代码中,虽然是两个字符串相减,但是依然会得到结果数值1,原因就在于 JavaScript 将运算子自动转为了数值。
javascript中的数据类型转换
在js中数据类型转换一般分为两种,即强制类型转换和隐式类型转换(利用js弱变量类型转换)。
显式类型转换主要通过使用JavaScript内置的函数来转换;
隐式类型转换是指JavaScript根据运算环境自动转换值的类型。
在js中,想要将对象转换成原始值,必然会调用toPrimitive()内部函数,那么它是如何工作的呢?
f35d6e602fd7d0f0edfa6f7d103c1b57 toPrimitive(input,preferedType)
input是输入的值,preferedType是期望转换的类型,他可以是String或者Number,也可以不传。
1)如果转换的类型是number,会执行以下步骤:
1. 如果input是原始值,直接返回这个值; 2. 否则,如果input是对象,调用input.valueOf(),如果结果是原始值,返回结果; 3. 否则,调用input.toString()。如果结果是原始值,返回结果; 4. 否则,抛出错误。
2) 如果转换的类型是String,2和3会交换执行,即先执行toString()方法。
3)可以省略preferedType,此时,日期会被认为是字符串,而其他的值会被当做Number。
①如果input是内置的Date类型,preferedType视为String
②否则视为Number,先调用valueOf,在调用toString
2cc198a1d5eb0d3eb508d858c9f5cbdbToBoolean(argument)
类型 | 返回结果 |
Underfined | false |
Null | false |
Boolean | argument |
Number | 仅当argument为+0,-0或者NaN时,return false;否则return true |
String | 仅当argument为空字符串(长度为0)时,return false;否则return true |
Symbol | true |
Object | true |
注意:除了underfined,null,false,NaN,’’,0,-0,其他都返回true
5bdf4c78156c7953567bb5a0aef2fc53ToNumber(argument)
类型 | 返回结果 |
Underfined | NaN |
Null | +0 |
Boolean | argument为true,return 1;为false,return +0 |
Number | argument |
String | 将字符串中的内容转化成数字,如'23'=>23;如果转化失败,则返回NaN,如‘23a’=>NaN |
Symbol | 抛出TypeError异常 |
Object | **先primValue= toPrimitive(argument,number),在对primValue使用ToNumber(primValue)** |
23889872c2e8594e0f446a471a78ec4cToString(argument)
类型 | 返回结果 |
Underfined | "underfined" |
Null | "null" |
Boolean | argument为true,return "true";为false,return "false" |
Number | 用字符串来表示这个数字 |
String | argument |
Symbol | 抛出TypeError异常 |
Object | **先primValue= toPrimitive(argument,string),在对primValue使用ToString(primValue)** |
1.隐式类型转换:
1.1-隐式转换介绍
· 在js中,当运算符在运算时,如果两边数据不统一,CPU就无法计算,这时我们编译器会自动将运算符两边的数据做一个数据类型转换,转成一样的数据类型再计算
这种无需程序员手动转换,而由编译器自动转换的方式就称为隐式转换
· 例如1 > "0"这行代码在js中并不会报错,编译器在运算符时会先把右边的"0"转成数字0`然后在比较大小
————————————————
1.2-隐式转换规则
(1). 转成string类型: +(字符串连接符)
(2).转成number类型:++/–(自增自减运算符) + - * / %(算术运算符) > 6d267e5fab17ea8bc578f9e7e5e1570b= 08dd2b91783750cd5369729f0b490a02 1+1=2
//xy有一边为string时,会做字符串拼接
console.log(1+'true') //String(1)+2 ==> '1true'
console.log('a'+ +'b') //aNaN
console.log(1+undefined) //1+Number(undefined)==>1+NaN=NaN
console.log(null+1) //Number(null)+1==>0+1=1
//2.会把其他数据类型转换成number之后再比较关系
//注意:左右两边都是字符串时,是要按照字符对应的unicode编码转成数字。查看字符串unicode的方法:字符串.charCodeAt(字符串下标,默认为0)
console.log('2'>'10') //'2'.charCodeAt()>'10'.charCodeAt()=50>49==>true
//特殊情况,NaN与任何数据比较都是NaN
console.log(NaN==NaN) //false
//3.复杂数据类型在隐式转换时,原始值(valueOf())不是number,会先转成String,然后再转成Number运算
console.log(false=={}) //false //({}).valueOf().toString()="[object Object]"
console.log([]+[]) //"" //[].valueOf().toString()+[].valueOf().toString()=""+""=""
console.log({}+[]) //0
console.log(({})+[]) //"[object Object]"
console.log(5/[1]) //5
console.log(5/null) //5
console.log(5+{toString:function(){return 'def'}}) //5def
console.log(5+{toString:function(){return 'def'},valueOf:function(){return 3}}) //5+3=8
//4.逻辑非隐式转换与关系运算符隐式转换搞混淆(逻辑非,将其他类型转成boolean类型)
console.log([]==0) //true
console.log({}==0) //false
console.log(![]==0) //true
console.log([]==![]) //true
console.log([]==[]) //false //坑
console.log({}=={}) //false //坑
console.log({}==!{}) //false //坑
2.强制类型(显式类型)转换:
通过手动进行类型转换,Javascript提供了以下转型函数:
转换为数值类型:Number(mix)、parseInt(string,radix)、parseFloat(string)
转换为字符串类型:toString(radix)、String(mix)
转换为布尔类型:Boolean(mix)
2.1 Boolean(value)、Number(value) 、String(value)
new Number(value) 、new String(value)、 new Boolean(value)传入各自对应的原始类型的值,可以实现“装箱”-----即将原始类型封装成一个对象。其实这三个函数不仅可以当作构造函数,还可以当作普通函数来使用,将任何类型的参数转化成原始类型的值。
其实这三个函数在类型转换的时候,调用的就是js内部的ToBoolean(argument)、ToNumber(argument)、ToString(argument)
2.2 parseInt(string,radix)
将字符串转换为整数类型的数值。它也有一定的规则:
(1)忽略字符串前面的空格,直至找到第一个非空字符
(2)如果第一个字符不是数字符号或者负号,返回NaN
(3)如果第一个字符是数字,则继续解析直至字符串解析完毕或者遇到一个非数字符号为止
(4)如果上步解析的结果以0开头,则将其当作八进制来解析;如果以0x开头,则将其当作十六进制来解析
(5)如果指定radix参数,则以radix为基数进行解析
let objj={ valueOf:function(){return '2px'}, toString:function(){return []} } parseInt(objj) //2 parseInt('001') //1 parseInt('22.5') //22 parseInt('123sws') //123 parseInt('sws123') //NaN //特殊的 parseInt(function(){},16) //15 parseInt(1/0,19) //18 //浏览器代码解析器:parseInt里面有两个参数,第二个参数是十九进制(0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i),额,1/0,好吧先运算 结果等于Infinity, //I好的十九进制有认识,n十九进制不存在不认识,不管后面有没有了,立即返回i(i对应的十进制中的18),所以返回18 parseInt(1/0,16) //NaN //同上,16进制灭有对应i,返回NaN parseInt(0.0000008) //8 //String(0.0000008),结果为8e-7 parseInt(0.000008) //0 parseInt(false,16) //250 //16进制,'f'认识, 'a'认识, 'l'哦,不认识,立即返回fa (十六进制的fa转换成十进制等于250) parseInt('0x10')) //16 //只有一个参数,好的,采用默认的十进制, '0x',额,这个我认识,是十六进制的写法, 十六进制的10转换成十进制等于16 parseInt('10',2) //2 //返回二进制的10 转换成十进制等于2
2.3 parseFloat(string)
将字符串转换为浮点数类型的数值.规则:
它的规则与parseInt基本相同,但也有点区别:字符串中第一个小数点符号是有效的,另外parseFloat会忽略所有前导0,如果字符串包含一个可解析为整数的数,则返回整数值而不是浮点数值。
2.4 toString(radix)
除undefined和null之外的所有类型的值都具有toString()方法,其作用是返回对象的字符串表示
【相关推荐:javascript学习教程】
以上是javascript中数据类型转换分为哪两种的详细内容。更多信息请关注PHP中文网其他相关文章!

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

html5aimstoenhancewebcapabilities,Makeitmoredynamic,互动,可及可访问。1)ITSupportsMultimediaElementsLikeAnd,消除innewingtheneedtheneedtheneedforplugins.2)SemanticeLelelemeneLementelementsimproveaCceccessibility inmproveAccessibility andcoderabilitile andcoderability.3)emply.3)lighteppoperable popperappoperable -poseive weepivewebappll

html5aimstoenhancewebdevelopmentanduserexperiencethroughsemantstructure,多媒体综合和performanceimprovements.1)SemanticeLementLike like,和ImproVereAdiability and ImproVereAdabilityAncccossibility.2)和TagsallowsemplowsemplowseamemelesseamlessallowsemlessemlessemelessmultimedimeDiaiiaemediaiaembedwitWithItWitTplulurugIns.3)

html5isnotinerysecure,butitsfeaturescanleadtosecurityrisksifmissusedorimproperlyimplempled.1)usethesand andboxattributeIniframestoconoconoconoContoContoContoContoContoconToconToconToconToconToconTedContDedContentContentPrevulnerabilityLikeClickLickLickLickLickLickjAckJackJacking.2)

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

使用ID选择器在CSS中并非固有地不好,但应谨慎使用。1)ID选择器适用于唯一元素或JavaScript钩子。2)对于一般样式,应使用类选择器,因为它们更灵活和可维护。通过平衡ID和类的使用,可以实现更robust和efficient的CSS架构。

html5'sgoalsin2024focusonrefinement和optimization,notnewfeatures.1)增强performandemandeffifice throughOptimizedRendering.2)risteccessibilitywithrefinedibilitywithRefineDatientAttributesAndEllements.3)expliencernsandelements.3)explastsecurityConcerns,尤其是withercervion.4)

html5aimedtotoimprovewebdevelopmentInfourKeyAreas:1)多中心供应,2)语义结构,3)formcapabilities.1)offlineandstorageoptions.1)html5intoryements html5introctosements introdements and toctosements and toctosements,简化了inifyingmediaembedingmediabbeddingingandenhangingusexperience.2)newsements.2)


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3汉化版
中文版,非常好用

Dreamweaver CS6
视觉化网页开发工具

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)