標籤:ring 字元 字串 oct efi ack str text doc
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 * - 類型轉換主要指,將其他的資料類型,轉換為12 * String Number Boolean13 * 14 */15 16 /*17 * 將其他的資料類型轉換為String18 * 方式一:19 * - 調用被轉換資料類型的toString()方法20 * - 該方法不會影響到原變數,它會將轉換的結果返回21 * - 但是注意:null和undefined這兩個值沒有toString()方法,如果調用他們的方法,會報錯22 * 23 * 方式二:24 * - 調用String()函數,並將被轉換的資料作為參數傳遞給函數25 * - 使用String()函數做強制類型轉換時,26 * 對於Number和Boolean實際上就是調用的toString()方法27 * 但是對於null和undefined,就不會調用toString()方法28 * 它會將 null 直接轉換為 "null"29 * 將 undefined 直接轉換為 "undefined"30 * 31 */32 33 var a = 123;34 35 //調用a的toString()方法36 //調用xxx的yyy()方法,就是xxx.yyy()37 a = a.toString();38 //console.log(typeof a); //string39 40 41 a = true;42 a = a.toString();43 //console.log(typeof a); //string44 45 a = null;46 //a = a.toString(); //報錯,Uncaught TypeError: Cannot read property ‘toString‘ of null47 48 a = undefined;49 //a = a.toString(); //報錯,Uncaught TypeError: Cannot read property ‘toString‘ of undefined50 51 52 a = 123;53 54 //調用String()函數,來將a轉換為字串55 a = String(a);56 //console.log(typeof a); //string57 58 a = null;59 a = String(a);60 //console.log(typeof a); //string61 62 a = undefined;63 a = String(a);64 //console.log(typeof a); //string65 66 //我用Java中的方法,發現也是可以的67 var b=123;68 b = ""+b;69 console.log(typeof b); //string70 71 72 73 74 </script>75 </head>76 <body>77 </body>78 </html>
JS基礎_強制類型轉換-String