迹忆客 专注技术分享

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

JavaScript 中 Cannot read property 'toLowerCase' of Undefined 错误

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

对未定义的值调用 toLowerCase() 方法时,会发生“Cannot read property 'toLowerCase' of Undefined”错误。 要解决此错误,需要将值初始化为空字符串或确保仅对字符串调用 toLowerCase 方法。

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

const str = undefined;

// ⛔️ TypeError: Cannot read properties of undefined (reading 'toLowerCase')
str.toLowerCase();

要解决此错误,请将变量的值初始化为空字符串,或确保仅对字符串调用 String.toLowerCase 方法。

const someVar = undefined;

// ✅ Initialize to empty string
const str = someVar || ''; // 👉️ ""

// ✅ Using ternary
const result1 = typeof str === 'string' ? str.toLowerCase() : '';
console.log(result1); // 👉️ ""

// ✅ Using optional chaining
const result2 = str?.toLowerCase() || '';
console.log(result2); // 👉️ ""

// ✅ Using if/else
if (typeof str === 'string') {
  const result3 = str.toLowerCase();
} else {
  console.log('str is not a string');
}

// ✅ Initialize to empty string
const result4 = (str || '').toLowerCase();
console.log(result4); // 👉️ ""

在声明 str 变量时,我们使用逻辑 OR || 运算符来提供回退,以防 someVar 存储虚假值(例如未定义)。

const someVar = undefined;

const str = someVar || ''; // 👉️ ""

下一个示例使用三元运算符,它与 if/else 语句非常相似。

const someVar = undefined;

const result1 = typeof str === 'string' ? str.toLowerCase() : '';
console.log(result1); // 👉️ ""

如果问号左边的表达式为假(例如 undefined),则返回冒号左边的值,否则返回冒号右边的值。

下一个示例使用可选的链接 ?. 运算符。 如果左边的值等于 nullundefined,运算符将短路而不是抛出错误。

const someVar = undefined;

const result2 = str?.toLowerCase() || '';
console.log(result2); // 👉️ ""

下一个示例使用一个简单的 if/else 语句,我们在调用 toLowerCase() 方法之前检查 str 变量存储的值是否为字符串。

const someVar = undefined;

if (typeof str === 'string') {
  const result3 = str.toLowerCase();
} else {
  console.log('str is not a string');
}

最后一个示例使用逻辑 OR || 运算符在值为 falsy 时提供回退。

const someVar = undefined;

const result4 = (str || '').toLowerCase();
console.log(result4); // 👉️ ""

发生“Cannot read property 'toLowerCase' of Undefined”错误的常见原因是:

  1. 在未初始化为字符串的类属性上调用方法
  2. 在不存在的数组索引上调用方法

下面是一个示例,显示使用数组时抛出的错误。

const arr = [];

// ⛔️ Cannot read properties of undefined (reading 'toLowerCase')
arr[0].toLowerCase();

要解决这个问题,我们必须确保索引处的元素可用且类型为字符串。

const arr = [];

const result = typeof arr?.[0] === 'string' ? arr[0].toLowerCase() : '';
console.log(result); // 👉️ ""

在调用 toLowerCase 方法之前,我们检查特定索引处的数组元素是否为字符串。

如果使用类,则必须在访问它之前声明类属性并将其设置为空字符串。

class Person {
  // ✅ Initialize to empty string
  last = '';

  // ✅ Initialize from parameters
  constructor(first) {
    this.first = first;
  }

  lowerFirst() {
    return this.first.toLowerCase();
  }

  lowerLast() {
    return this.last.toLowerCase();
  }
}

const p1 = new Person('John');
p1.lowerFirst();
p1.lowerLast();

我们初始化了第一个和最后一个类属性的值。 如果我们不这样做,我们将在尝试访问属性时遇到错误。


总结

对未定义的值调用 toLowerCase() 时,会发生“Cannot read property 'toLowerCase' of Undefined”错误。

要解决该错误,请确保仅对字符串调用 toLowerCase 方法。

转载请发邮件至 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便