Uncaught TypeError: Cannot read properties of undefined(reading 'length')

2,254 阅读1分钟

解决-无法读取未定义的属性“长度”

要解决该错误,请确保仅访问支持'length'的数据类型的属性-数组或字符串。

image.png

这是错误发生的实例。

image.png 要解决此错误,请在访问属性之前为该值提供备选值。

const fromDb = undefined;

// 提供空数组做备胎
const arr = fromDb || [];

// 使用可选运算符?.
const result1 = arr?.length;
console.log(result); // ✅ undefined

// 如果未定义,可选择0作为备胎
const result2 = arr?.length || 0;

// 使用 Array.isArray
if(Array.isArray(arr)){
    const result3 = arr.length;
} else {
    console.log('arr is not an array');
}

const result4 = (arr || []).length;

下面显示了相同的解决方案,但是用于字符串

const fromDb = undefined;

const str = fromDb || '';

const result1 = str?.length;

const result2 = str?.length || 0;

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

const result4 = (str || '').length;

如果左边的值是假的,使用短路运算符||(找真),返回右边的值。

还可以使用可选运算符?.进行短路undefined、null

还可以使用Array.isArray方法检查是否为数组或使用typeof检查是否为字符串

还可以使用三元运算符。如果问号左边的值是真的,则返回冒号左边的值,否则返回冒号右边的值。

const str = undefined;

const result = str ? str.length : 0;
console.log(result); // ✅ 0

结论

要解决此bug,请仅访问支持length的数据类型的属性 - 数组或字符串。