JavaScript隱式類型轉(zhuǎn)換代碼實例
值類型之間的數(shù)據(jù)類型轉(zhuǎn)換:
(1)數(shù)字和字符串使用+運算符:
數(shù)字和字符串如果使用+運算符進行操作,那么會將數(shù)字先轉(zhuǎn)換為字符串,然后進行字符串連接操作:
var str = 'string text ';var num = 10;console.log(str + num) // 'string text 10'
(2)布爾值參與的+運算符操作:
如果有布爾型參與,那么首先會將布爾值轉(zhuǎn)換為對應(yīng)的數(shù)字或者字符串,然后再進行相應(yīng)的字符串連接或者算數(shù)運算。
var num = 12;var bool = true;var str = 'text';console.log(num + bool) //13console.log(str + bool) // 'text true'
(3)Null和Undefined參與的+運算符操作
如果和數(shù)字進行計算,null會轉(zhuǎn)化為0,undefined會轉(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)的字符串值再進行操作
var a;var str=’123’;console.log(a + str);//’undefined123’var a=null;var str=’123’;console.log(a + str);//’null123’
(4)==等性運算:
undefined和null比較特殊,它們兩個使用==運算符返回值是true。
其他值類型(Number、Boolean、Null、Undefined)進行比較的時候都會將運算數(shù)轉(zhuǎn)換為數(shù)字
console.log(undefined == null); // trueconsole.log('1' ==true); //true
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. PHP使用Swagger生成好看的API文檔2. ASP.NET MVC使用jQuery ui的progressbar實現(xiàn)進度條3. Python3 json模塊之編碼解碼方法講解4. Python 制作查詢商品歷史價格的小工具5. Python 如何調(diào)試程序崩潰錯誤6. Python 利用Entrez庫篩選下載PubMed文獻摘要的示例7. ASP基礎(chǔ)知識VBScript基本元素講解8. python使用jenkins發(fā)送企業(yè)微信通知的實現(xiàn)9. Python sublime安裝及配置過程詳解10. Python 合并拼接字符串的方法

網(wǎng)公網(wǎng)安備