JavaScript 中的 const 和 let。
ES2015 引入了 const 和 let 来声明块级作用域的变量。使用 let 声明的变量可以重新分配,但如果使用 const 声明则无法重新分配。
以下代码展示了 JavaScript 中的 let 和 const -
示例
<!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>Const and let in JavaScript</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 reassign const and let value</h3> <script> let resEle = document.querySelector(".result"); let sampleEle = document.querySelector(".sample"); let a = 22; const b = 44; sampleEle.innerHTML = "let a = " + a + " "; sampleEle.innerHTML += "const b = " + b; document.querySelector(".Btn").addEventListener("click", () => { a = 99; resEle.innerHTML = "Reassigning a = " + a + " "; try { changeB(); } catch (err) { resEle.innerHTML += "Reassigning b = " + err; } }); function changeB() { b = 22; } </script> </body> </html>
输出
上述代码将生成以下输出 -
单击“点击此处”按钮时 -
广告