JavaScript 中 Cannot read property 'toUpperCase' of Undefined 错误
对未定义的值调用 toUpperCase()
方法时,会发生“Cannot read property 'toUpperCase' of Undefined”错误。 要解决此错误,需要将值初始化为空字符串或确保仅对字符串调用 toUpperCase()
方法。
下面是产生上述错误的示例代码
const str = undefined;
// ⛔️ TypeError: Cannot read properties of undefined (reading 'toUpperCase')
str.toUpperCase();
要解决此错误,请将变量的值初始化为空字符串,或确保仅对字符串调用 String.toUpperCase
方法。 这里有些例子。
const myVar = undefined;
// ✅ Provide empty string fallback
const str = myVar || ''; // 👉️ ""
// ✅ Using ternary operator
const r1 = typeof str === 'string' ? str.toUpperCase() : '';
console.log(r1); // 👉️ ""
// ✅ Using optional chaining (?.)
const r2 = str?.toUpperCase() || '';
console.log(r2); // 👉️ ""
// ✅ Using if/else
if (typeof str === '') {
const r3 = str.toUpperCase();
} else {
console.log('str is not a string');
}
// ✅ Provide empty string fallback
const r4 = (str || '').toUpperCase();
console.log(r4); // 👉️ ""
在声明 str 变量时,我们使用逻辑 OR ||
运算符来提供回退,以防 myVar 存储虚假值(例如 undefined
)。
const myVar = undefined;
const str = myVar || ''; // 👉️ ""
console.log(str.toUpperCase()); // 👉️ ""
下一个示例使用三元运算符,它与 if/else
语句非常相似。
const str = undefined;
const r1 = typeof str === 'string' ? str.toUpperCase() : '';
console.log(r1); // 👉️ ""
如果问号左边的表达式是假的(例如
undefined
),则返回冒号左边的值,否则返回冒号右边的值。
下一个示例使用可选的链接 ?.
运算符。
const str = undefined;
const r2 = str?.toUpperCase() || '';
console.log(r2); // 👉️ ""
如果左侧的值等于 undefined 或 null,则可选链接 ?.
运算符会短路而不是抛出错误。
下一个示例使用一个简单的 if/else
语句,在调用 toUpperCase()
方法之前检查值是否为字符串。
const str = undefined;
if (typeof str === '') {
const r3 = str.toUpperCase();
} else {
console.log('str is not a string');
}
最后一个示例使用逻辑 OR ||
运算符在值为 falsy 时提供回退。
const str = undefined;
const r4 = (str || '').toUpperCase();
console.log(r4); // 👉️ ""
发生“Cannot read property 'toUpperCase' of Undefined”错误的常见原因是:
- 在未初始化为字符串的类属性上调用方法。
- 在不存在的数组索引上调用方法。
下面是一个示例,显示使用数组时抛出的错误。
const arr = [];
// 👇️ Cannot read properties of undefined (reading 'toUpperCase')
arr[0].toUpperCase();
要解决这个问题,我们必须确保索引处的元素可用并且是一个字符串。
const arr = [];
const result = typeof arr?.[0] === 'string' ? arr[0].toUpperCase() : '';
console.log(result); // 👉️ ""
在调用 toUpperCase
方法之前,我们检查特定索引处的数组元素是否为字符串。
如果使用类,则必须在访问它之前声明类属性并将其设置为空字符串。
class Person {
// ✅ Initialize to empty string
last = '';
// ✅ Initialize from parameters
constructor(first) {
this.first = first;
}
upperFirst() {
return this.first.toUpperCase();
}
upperLast() {
return this.last.toUpperCase();
}
}
const p1 = new Person('Tom');
p1.upperFirst();
p1.upperLast();
我们初始化了第一个和最后一个类属性的值。 如果我们不这样做,我们将在尝试访问属性时遇到错误。
结论
在未定义的值上调用 toUpperCase()
时,会发生“Cannot read property 'toUpperCase' of Undefined”错误。
要解决该错误,请确保仅对字符串调用 toUpperCase
方法。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。