JavaScript 中的“TypeError: ‘undefined’ is not an object”
在未定义的对象上访问属性或调用方法时,会发生“TypeError: ‘undefined’ is not an object”错误。该错误只在 Safari 浏览器中显示。
以下是在 JavaScript 中“TypeError - ‘undefined’ is not an object”的代码错误 −
示例
<!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:blueviolet } </style> </head> <body> <h1>TypeError: ‘undefined’ is not an object example</h1> <div class="result"></div> <br /> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to access the name property of person object</h3> <script> var resEle = document.querySelector('.result'); var BtnEle = document.querySelector('.Btn'); var person; BtnEle.addEventListener('click',function(){ try{ alert(person.name); } catch(err){ resEle.innerHTML=err; } }); </script> </body> </html>
输出
点击“点这里”按钮 −
广告