JavaScript 中 TypeError: Cannot read Property 'split' of Null 错误
当对存储空值的变量调用 split()
方法时,会发生“Cannot read Property 'split' of Null”错误。 要解决该错误,请确保仅对字符串调用 split()
方法。
下面是产生上述错误的示例代码
const str = null;
// ⛔️ TypeError: Cannot read properties of null (reading 'split')
console.log(str.split(','));
要解决该错误,请在变量存储虚假值时提供回退,例如 一个空字符串。
const text = null;
const str = text || '';
console.log(str.split(',')); // 👉️ ['']
如果左边的值是假的(例如 null),逻辑 OR
||
运算符返回右边的值。
我们还可以在调用 split()
方法之前有条件地检查变量是否存储字符串。
const str = null;
// ✅ Check if str is of type string
if (typeof str === 'string') {
const arr = str.split(',');
console.log(arr);
} else {
console.log('str is not a string');
}
// ✅ Use optional chaining
const result = str?.split(','); // 👉️ undefined
第一个示例使用 if
语句来检查 str 变量是否存储了字符串类型的值。
if
块仅在值为字符串时运行,因此我们可以安全地调用split()
方法。
第二个示例使用可选的链接 ?.
运算符,如果左侧的值为 null 或 undefined,它会短路返回 undefined。
如果 str 变量不等于 null 或 undefined,运算符将仅调用 split()
方法。
总结
在存储空值的变量上调用 split()
方法时,会发生“TypeError: Cannot read Property 'split' of Null”错误。
为避免出现错误,需要确保变量在调用 split()
方法之前存储了一个字符串。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。