TypeError: 'undefined' 不是 JavaScript 中的对象
javascriptweb developmentobject oriented programming更新于 2025/8/27 8:12:17
当访问未定义对象的属性或调用其方法时,会发生 “TypeError: ‘undefined’ 不是对象” 错误。此错误仅在 Safari 浏览器上显示。
以下是 JavaScript 中 TypeError − ‘undefined’ 不是对象错误的代码 −
示例
<!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">点击此处</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>
输出

点击‘点击此处’按钮 −

相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

