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()內部函數,那麼它是如何運作的呢?
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
ToBoolean( 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 |
注意: | |
ToNumber(argument) | |
#類型 | 傳回結果 |
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)** |
#ToString(argument) | |
#類型 | 傳回結果 |
1.隐式类型转换:
1.1-隐式转换介绍
· 在js中,当运算符在运算时,如果两边数据不统一,CPU就无法计算,这时我们编译器会自动将运算符两边的数据做一个数据类型转换,转成一样的数据类型再计算
这种无需程序员手动转换,而由编译器自动转换的方式就称为隐式转换
· 例如1 > "0"这行代码在js中并不会报错,编译器在运算符时会先把右边的"0"转成数字0`然后在比较大小
————————————————
1.2-隐式转换规则
(1). 转成string类型: +(字符串连接符)
(2).转成number类型:++/–(自增自减运算符) + - * / %(算术运算符) > =
加法规则
1.令lval=符号左边的值,rval=符号右边的值
2.令lprim=toPrimitive(lval),rprim=toPrimitive(rval)
如果lprim和rprim中有任意一个为string类型,将ToString(lprim)和ToString(rprim)的结果做字符串拼接
否则,将ToNumber(lprim)和ToNumber(rprim)的结果做算数加法
双等规则
1.xy都为Null或者underfined,return true;一方为Null或者underfined、NaN,return false
2.如果x和y为String,Number,Boolean并且类型不一致,都转为Number在进行比较
3.如果存在Object,转换为原始值在进行比较
//特殊情况,xy都为Null或者underfined,return true console.log(undefined==undefined) //true console.log(undefined==null) //true console.log(null==null) //true //一方为Null或者underfined、NaN,return false console.log("0"==null) //false console.log("0"==undefined) //false console.log("0"==NaN) //false console.log(false==null) //false console.log(false==undefined) //false console.log(false==NaN) //false console.log("0"=="") //false console.log("0"==0) //true console.log(""==[]) //true console.log(false==0) //true console.log(false==[]) //true
(3). 转成boolean类型:!(逻辑非运算符)
//1.字符串连接符与算术运算符隐式转换规则易混淆 console.log(1+true) // 1+Number(true) ==> 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 ImproVereAdabilityActibility.2)and tagsallowsemlessallowseamelesseamlessallowseamelesseamlesseamelesseamemelessmultimedimeDiaiaembediiaembedplugins.3)。 3)3)

html5isnotinerysecure,butitsfeaturescanleadtosecurityrisksifmissusedorimproperlyimplempled.1)usethesand andboxattributeIniframestoconoconoconoContoContoContoContoContoconToconToconToconToconToconTedContDedContentContentPrenerabilnerabilityLikeClickLickLickLickjAckJackJacking.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)增強performanceandeffipedroptimizedRendering.2)inviveAccessibilitywithRefinedwithRefinedTributesAndEllements.3)explityconcerns,尤其是withercercern.4.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
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。