JS基礎_強制類型轉換-String


 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title></title>
 6         <script type="text/javascript">
 7             
 8             /*
 9  * 強制類型轉換 10  * - 指將一個數據類型強制轉換為其他的數據類型 11  * - 類型轉換主要指,將其他的數據類型,轉換為String 、Number 、Boolean 12  * 13              */
14             
15             /*
16  * 將其他的數據類型轉換為String 17  * 方式一: 18  * - 調用被轉換數據類型的toString()方法 19  * - 該方法不會影響到原變量,它會將轉換的結果返回 20  * - 但是注意:null和undefined這兩個值沒有toString()方法,如果調用他們的方法,會報錯 21  * 22  * 方式二: 23  * - 調用String()函數,並將被轉換的數據作為參數傳遞給函數 24  * - 使用String()函數做強制類型轉換時, 25  * 對於Number和Boolean實際上就是調用的toString()方法 26  * 但是對於null和undefined,就不會調用toString()方法 27  * 它會將 null 直接轉換為 "null" 28  * 將 undefined 直接轉換為 "undefined" 29  * 30              */
31             
32             //1.調用被轉換數據類型的toString()方法
33             var a = 123; 34  a = a.toString(); 35  console.log(typeof a); //string
36             
37             
38  a = true; 39  a = a.toString(); 40  console.log(typeof a); //string
41             
42  a = null; 43  a = a.toString(); 44  console.log(typeof a); //報錯,Uncaught TypeError: Cannot read property 'toString' of null
45             
46  a = undefined; 47  a = a.toString(); 48  console.log(typeof a); //報錯,Uncaught TypeError: Cannot read property 'toString' of undefined
49             
50             //---------------------------------------------------------------------------------------------
51             
52             //2.調用String()函數,並將被轉換的數據作為參數傳遞給函數
53  a = 123; 54  a = String(a); 55  console.log(typeof a); //string
56             
57  a = null; 58  a = String(a); 59  console.log(typeof a); //string
60             
61  a = undefined; 62  a = String(a); 63  console.log(typeof a); //string
64             
65             //3.我用Java中的方法,發現也是可以的
66             var b = 123; 67  b = "" + b; 68  console.log(typeof b); //string
69             
70             
71             
72             
73         </script>
74     </head>
75     <body>
76     </body>
77 </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM