JavaScript 字串 toString() 方法



JavaScript 字串 toString() 方法返回其被呼叫的字串物件或原始值的字串表示形式。它不會修改原始字串。當字串物件在上下文中使用時,JavaScript 會自動呼叫此方法。

語法

以下是 JavaScript 字串 toString() 方法的語法:

toString()

引數

  • 它不接受任何引數。

返回值

此方法返回字串值本身。

示例 1

以下示例演示了 JavaScript 字串 toString() 方法的使用。

<html>
<head>
<title>JavaScript String toString() Method</title>
</head>
<body>
<script>
   const str = "Tutorials Point";
   document.write("String value(str): ", str);
   document.write("<br>The str.toString() method returns: ", str.toString());
</script>    
</body>
</html>

輸出

上述程式返回“Tutorials Point”。

String value(str): Tutorials Point
The str.toString() method returns: Tutorials Point

示例 2

以下是 JavaScript 字串 toString() 方法的另一個示例。在這裡,我們呼叫字串物件引用變數上的此方法以檢索物件的值。正如我們所討論的,當建立(使用)字串物件時,此方法會自動呼叫,但如果在控制檯中列印引用變數值,它將顯示為 String {"value"}。

<html>
<head>
<title>JavaScript String toString() Method</title>
</head>
<body>
<script>
   const strObj = new String("Hello World");
   console.log("The strObj value: ", strObj);
   // it will print String{"Hello World"};
   document.write("The strObj.toString() method returns: ", strObj.toString());
   // it will print "Hello World";
</script>    
</body>
</html>

輸出

執行上述程式後,它將返回“Hello World”。

The strObj.toString() method returns: Hello World
廣告

© . All rights reserved.