Javascript 中 TypeError: Cannot read property 'X' of NULL 错误
出现“Cannot read properties of null (reading 'X')”错误的主要原因有 3 个:
- 访问存储空值的变量的属性。
- 访问不存在的 DOM 元素的属性。
- 在声明 DOM 元素的 HTML 上方插入 JS 脚本标记。
如果大家尝试访问存储空值的变量的属性,例如 不存在的 DOM 元素。
这是一个例子。
const example = null;
// ⛔️ Uncaught TypeError: Cannot read properties of null
// (reading 'value')
example.value;
我们试图访问导致错误的 null 值的属性。
这是另一个例子。
const el = null;
// ⛔️ Uncaught TypeError: Cannot read properties of null
// (reading 'click')
el.click();
访问空值的属性
解决“Cannot read properties of null (reading 'X')”错误的一种方法是使用可选的链接 ?.
运算符,例如 obj?.address?.street
。
如果引用为空,可选的链接运算符将短路而不是抛出错误。
const example = null;
console.log(example?.value); // 👉️ undefined
console.log(example?.value?.moreNested); // 👉️ undefined
如果左侧的值为空值(null 或 undefined),则可选链接 ?.
运算符短路并返回 undefined。
我们还可以以类似的方式使用逻辑与 &&
运算符。
const example = null;
// 👇️ null
console.log(example && example.value && example.value.nested);
如果运算符左边的值是假的(例如 null),它不会计算右边的表达式,这样可以防止抛出错误。
在访问属性之前确保 DOM 元素存在
使用 DOM 元素时,“Cannot read properties of null (reading 'X') ”错误的发生有两个主要原因:
- 访问不存在的 DOM 元素的属性。
- 将 JS 脚本标记放在 index.html 文件中创建 DOM 元素的代码上方。
在使用 getElementById()
方法并向其传递一个不存在的 ID 后尝试访问属性时,通常会抛出该错误。
const el = document.getElementById('does-not-exist');
console.log(el); // null
// ⛔️ TypeError: Cannot read properties of null (reading 'value')
console.log(el.value);
我们指定了一个不存在的 id,并从 getElementById
方法中获得了一个空值。
尝试访问空值上的属性会导致错误。
确保我们访问的是正确的 DOM 元素,并添加条件检查以确保该元素在访问其属性之前存在。
const el = document.getElementById('not-exist');
console.log(el); // null
// ✅ 在访问属性之前检查元素是否存在
if (el?.value) {
console.log(el.value);
} else {
// 👇️ this runs
console.log('element does not exist');
}
如果 el 变量存储一个 null 或 undefined 值,我们不会得到错误,相反我们短路返回 undefined 并且我们的 else 块运行。
将我们的 JS 脚本标签放在 body 标签的底部
“Cannot read properties of null (reading 'X') ”错误的另一个常见原因是将 JS 脚本标记放在 index.html 文件中创建 DOM 元素的代码之上。
JS 脚本标签应该放在 HTML 元素声明之后。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<script src="index.js"></script>
<!-- ⛔️ BAD - 应该在 script 标签之上 ⛔️ -->
<input id="first_name" value="John" />
</body>
</html>
index.js 脚本位于输入元素上方,因此它无权访问它。
const el = document.getElementById('first_name');
console.log(el); // 👉️ null
// ⛔️ TypeError: Cannot read properties of null (reading 'value')
console.log(el.value);
在声明 HTML 元素之后,我们必须将 JS 脚本移动到正文的底部。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<!-- ✅️ GOOD - JS 脚本之上的 HTML 元素 ✅️ -->
<input id="first_name" value="John" />
<script src="index.js"></script>
</body>
</html>
现在我们可以访问 index.js 脚本中的 input 元素。
const el = document.getElementById('first_name');
console.log(el);
// ✅ works
console.log(el.value); // 👉️ "John"
HTML 代码是从上到下解析的,因此 script 标签必须放在 body 标签的底部,在它需要访问的所有 DOM 元素之后。
总结
要解决“Cannot read properties of null (reading 'X')”,请确保:
- 我们不是要访问存储空值的变量的属性。
- 我们不是在尝试访问不存在的 DOM 元素上的属性。
- 我们没有在 index.html 文件中声明 DOM 元素的 HTML 上方放置 JS 脚本标记。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。