JavaScript隱式類型轉(zhuǎn)換代碼實(shí)例
值類型之間的數(shù)據(jù)類型轉(zhuǎn)換:
(1)數(shù)字和字符串使用+運(yùn)算符:
數(shù)字和字符串如果使用+運(yùn)算符進(jìn)行操作,那么會(huì)將數(shù)字先轉(zhuǎn)換為字符串,然后進(jìn)行字符串連接操作:
var str = 'string text ';var num = 10;console.log(str + num) // 'string text 10'
(2)布爾值參與的+運(yùn)算符操作:
如果有布爾型參與,那么首先會(huì)將布爾值轉(zhuǎn)換為對(duì)應(yīng)的數(shù)字或者字符串,然后再進(jìn)行相應(yīng)的字符串連接或者算數(shù)運(yùn)算。
var num = 12;var bool = true;var str = 'text';console.log(num + bool) //13console.log(str + bool) // 'text true'
(3)Null和Undefined參與的+運(yùn)算符操作
如果和數(shù)字進(jìn)行計(jì)算,null會(huì)轉(zhuǎn)化為0,undefined會(huì)轉(zhuǎn)化成NaN
注意:Null轉(zhuǎn)換為0,Undefined轉(zhuǎn)換成NaN
console.log(undefined + 1) //NaNconsole.log(null + 1) // 1
首先調(diào)用string()方法,取得相應(yīng)的字符串值再進(jìn)行操作
var a;var str=’123’;console.log(a + str);//’undefined123’var a=null;var str=’123’;console.log(a + str);//’null123’
(4)==等性運(yùn)算:
undefined和null比較特殊,它們兩個(gè)使用==運(yùn)算符返回值是true。
其他值類型(Number、Boolean、Null、Undefined)進(jìn)行比較的時(shí)候都會(huì)將運(yùn)算數(shù)轉(zhuǎn)換為數(shù)字
console.log(undefined == null); // trueconsole.log('1' ==true); //true
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 以PHP代碼為實(shí)例詳解RabbitMQ消息隊(duì)列中間件的6種模式2. Python 如何將integer轉(zhuǎn)化為羅馬數(shù)(3999以內(nèi))3. python web框架的總結(jié)4. 詳解Python模塊化編程與裝飾器5. Python通過format函數(shù)格式化顯示值6. html小技巧之td,div標(biāo)簽里內(nèi)容不換行7. python裝飾器三種裝飾模式的簡(jiǎn)單分析8. Python如何進(jìn)行時(shí)間處理9. Python實(shí)現(xiàn)迪杰斯特拉算法過程解析10. python使用ctypes庫(kù)調(diào)用DLL動(dòng)態(tài)鏈接庫(kù)
