如何在 JavaScript 中创建常量?举例说明。

javascriptweb developmentobject oriented programming更新于 2025/8/19 1:16:17

以下是在 JavaScript 中创建常量的代码 −

示例

<!DOCTYPE html>
<html>
<head>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
</style>
</head>
<body>
<h1>Const example</h1>
<button class="btn">点击此处</button>
<p class="sample"></p>
<h3>Click the above button to try changing const value</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   const a = 33;
   sampleEle.innerHTML = "a = " + a + "<br>";
   document.querySelector(".Btn").addEventListener("click", () => {
      try {
         a = 44;
      }
      catch (err) {
         sampleEle.innerHTML += "Error : " + err;
      }
   });
</script>
</body>
</html>

输出

上述代码将产生以下输出 −

点击‘单击此处’按钮更改常量值−


相关文章


有用资源