JS轉換成字符串類型的三種方法


Js變量轉為字符串類型的方法有以下3種,大家可以根據場景選擇適合的方法,下面我們一一介紹。

1. toString()用法

語法:

變量 = 變量.toString();

案例:

<script>
    var num = 5;
    num = num.toString();
    console.log(num, typeof(num));    // 輸出字符串 5 string
</script>

通過上圖中可以看出,toString()方法已經將num轉為字符串類型。


2. String()

語法:

變量 = String(變量);

案例:

<script>
    var s = '10';
    s = String(s);
    console.log(s, typeof(s));// 輸出10 String
</script>

拓展:toString()和string() 有什么不同

除了使用的語法不同之外,最大的區別是有些值無法通過toString()轉化,如:undefined和null。

 

案例:

<script>
    var s = null;
    // s = s.toString()  報錯
    s = String(s);                  // 運行正常           
    console.log(s, typeof(s));// 輸出10 String
</script>


3. 拼接字符串

通過字符串拼接可以將非字符串轉為字符串類型,我們通過下面案例演示:

<script>
    var a = 10, b = true, c = undefined, d = null, e = '你好';
    console.log(a + '');        // 輸出字符串 10
    console.log(b + '');        // 輸出字符串 true
    console.log(c + '');        // 輸出字符串 undefined
    console.log(d + '');        // 輸出字符串 null
    console.log(a + '10');      // 輸出字符串 1010
    console.log(e + a);         // 輸出字符串 你好10
</script>

  

 


免責聲明!

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



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