如何验证 JavaScript 变量是否已加载?
要验证一个 JavaScript 变量是否已加载,我们可以通过对其未定义或为空值的情况进行比较来检查。我们也可以使用 typeof(),因为它总会返回字符串来了解变量是否已加载。
以下是验证 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: 20px; font-weight: 500; } </style> </head> <body> <h1>Check if a variable is loaded or not</h1> <div style="color: green;" class="result"></div> <button class="Btn">CLICK HERE</button> <h3> Click on the above button to see if the object obj has been loaded or not </h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let obj; BtnEle.addEventListener("click", () => { if (obj === null || obj === undefined) { resEle.innerHTML = "The object obj hasn't loaded yet"; obj = { firstName: "Rohan", lastName: "Sharma" }; } else { resEle.innerHTML = "The object obj has been loaded"; } }); </script> </body> </html>
输出
以上代码将产生以下输出 −
点击“单击此处”按钮 −
再次点击“单击此处”按钮 −
广告