迹忆客 专注技术分享

当前位置:主页 > 学无止境 >

JavaScript 中 TypeError: Cannot read Property 'split' of Null 错误

作者:迹忆客 最近更新:2023/01/01 浏览次数:

当对存储空值的变量调用 split() 方法时,会发生“Cannot read Property 'split' of Null”错误。 要解决该错误,请确保仅对字符串调用 split() 方法。

下面是产生上述错误的示例代码

const str = null;

// ⛔️ TypeError: Cannot read properties of null (reading 'split')
console.log(str.split(','));

JavaScript 中 TypeError- Cannot read Property 'split' of Null

要解决该错误,请在变量存储虚假值时提供回退,例如 一个空字符串。

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() 方法。

第二个示例使用可选的链接 ?. 运算符,如果左侧的值为 nullundefined,它会短路返回 undefined

如果 str 变量不等于 nullundefined,运算符将仅调用 split() 方法。


总结

在存储空值的变量上调用 split() 方法时,会发生“TypeError: Cannot read Property 'split' of Null”错误。

为避免出现错误,需要确保变量在调用 split() 方法之前存储了一个字符串。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便