JavaScript Symbol.for() 函数
javascriptweb developmentobject oriented programming
Symbol.for() 函数在运行时范围内的符号寄存器中搜索给定的符号。如果找到该符号,则返回该符号,否则在全局符号寄存器中创建一个新符号并直接返回。
以下是 symbol.for() 函数的代码
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } div { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>JavaScript Symbol.for() function</h1> <div class="sample"></div> <button class="btn">点击此处</button> <h3> Click on the above button to get the symbols. </h3> <script> let fillEle = document.querySelector(".sample"); let symbol = []; symbol.push(Symbol.for("New")); symbol.push(Symbol.for("Hello")); symbol.push(Symbol.for(345)); document.querySelector(".Btn").addEventListener("click", () => { symbol.forEach((item) => (fillEle.innerHTML += item.toString() + "<br>")); }); </script> </body> </html>
输出
点击“CLICK HERE”按钮 −