说明 JavaScript 中的枚举类型。
JavaScript 本身不支持枚举。在 javaScript 中使用枚举的唯一方法是使用对象来实现它们。
以下是 JavaScript 中枚举类型的代码演示 −
示例
<!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; } .result { font-size: 18px; font-weight: 500; color: rebeccapurple; } </style> </head> <body> <h1>Enumerated Types in JavaScript</h1> <div class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to get the color values</h3> <script> let resEle = document.querySelector(".result"); let color = { orange: 1, red: 2, green: 3, blue: 4, pink: 5, }; document.querySelector(".Btn").addEventListener("click", () => { resEle.innerHTML += "color.orange = " + color.orange + "<br>"; resEle.innerHTML += "color.red = " + color.red + "<br>"; resEle.innerHTML += "color.green = " + color.green + "<br>"; resEle.innerHTML += "color.blue = " + color.blue + "<br>"; resEle.innerHTML += "color.pink = " + color.pink + "<br>"; }); </script> </body> </html>
输出
以上代码将生成以下输出 −
单击“单击此处”按钮时 −
广告