JavaScript - Symbol.for() 方法



在 JavaScript 中,符號是一種基本資料型別,它被新增用來建立唯一的識別符號。符號對於在各種上下文中建立鍵(例如物件屬性或 Map 鍵)很有用,因為它們保證是唯一的,不像字串。

Symbol.for() 方法接受符號的描述,並在全域性符號登錄檔中搜索具有給定描述的符號。如果在現有的符號中找到了提供的描述,則返回該符號;否則,它會建立一個新的符號並將其新增到全域性登錄檔中。

語法

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

Symbol.for(key)

引數

此方法只接受一個引數。下面描述了該引數:

  • key - 它是符號的鍵,也用作符號的描述。

返回值

此方法如果找到具有給定鍵的現有符號,則返回該符號,否則建立一個新符號並返回。

示例

示例 1

讓我們看看下面的示例,我們將建立符號並檢索它。

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

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

示例 2

考慮下面的示例,我們將使用符號作為物件屬性。

<html>
   <style>
      p {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <p id="demo"></p>
      <script>
         const obj = {
            [Symbol.for('examp1')]: 'TP',
            [Symbol.for('examp2')]: 'TutorialsPoint'
         };
         document.getElementById('demo').innerHTML = obj[Symbol.for('examp2')];
      </script>
   </body>
</html>

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

示例 3

在下面的示例中,我們將檢查是否存在具有給定鍵的符號。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const key = Symbol.for('tp');
         if (Symbol.keyFor(key)) {
            document.write('Yes, The Symbol Exists.');
         } else {
            document.write('No, The Symbol Doesnt Exists.');
         }
      </script>
   </body>
</html>

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

示例 4

以下是示例,我們將從符號中獲取鍵。

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

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

廣告