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] = 'QikepuCom';
document.write(obj[x]);
</script>
</body>
</html>
在执行上述脚本时,将弹出输出窗口,在网页上显示文本。