如何在 JavaScript 中声明块级作用域变量?
要声明块级作用域变量,我们使用 ES2015 中引入的关键字 let 和 const。
以下是展示如何在 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,.sample { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>Declaring block scoped variables</h1> <div class="sample"></div> <div style="color: green;" class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to declare and display block scoped variables</h3> <script> let resEle = document.querySelector(".result"); let sampleEle = document.querySelector(".sample");{ let a = 22; const b = 44; sampleEle.innerHTML = "let a = " + a + "<br>"; sampleEle.innerHTML += "const b = " + b + "<br>"; } document.querySelector(".Btn").addEventListener("click", () => { try { a + b; } catch (err) { resEle.innerHTML = "a+b = " + err; } }); </script> </body> </html>
输出
上述代码将生成以下输出 −
单击“点击此按钮”按钮 −
广告