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>

执行上述脚本后,将弹出输出窗口,在网页上显示文本。

广告

© . All rights reserved.