JavaScript - Symbol.toString() 方法



Symbol.toString() 方法是一個內建函式,允許您獲取 Symbol 物件的字串表示形式。在 JavaScript 中,符號是一種基本資料型別,用於生成唯一 ID。符號對於指定應彼此分開的物件屬性很有用,因為與字串或數字不同,它們是唯一且不可變的。

當在符號例項上呼叫時,它會返回表示該符號的字串。當符號在上下文中強制轉換為字串時,例如使用模板字面量或字串連線,此方法會自動呼叫。

語法

以下是 JavaScript Symbol.tostring() 方法的語法:

Symbol().toString()

引數

此方法不接受任何引數。

返回值

此方法返回指定符號物件的已轉換字串。

示例

示例 1

讓我們看看下面的示例,我們將看到 symbol.tostring() 方法的基本用法。

<html>
   <style>
      p {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <p id="demo"></p>
      <script>
         const x = Symbol('TP');
         document.getElementById('demo').innerHTML = x.toString();
      </script>
   </body>
</html>

如果我們執行上述程式,它將在網頁上顯示文字。

示例 2

考慮下面的示例,我們將使用隱式強制轉換(自動將一種資料型別轉換為另一種資料型別)。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = Symbol('Welcome');
         const y = String(x);
         document.write(y);
      </script>
   </body>
</html>

執行上述指令碼後,它將在網頁上顯示文字。

示例 3

在下面的示例中,我們將建立一個描述為空的符號。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = Symbol('');
         document.write(x.toString());
      </script>
   </body>
</html>

當我們執行指令碼時,它將在網頁上顯示文字。

示例 4

以下是示例,我們將使用符號作為屬性鍵。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = Symbol('tp');
         const obj = {};
         obj[x] = 'TutorialsPoint';
         document.write(obj[x]);
      </script>
   </body>
</html>

執行上述指令碼後,將彈出輸出視窗,在網頁上顯示文字。

廣告