解决-无法读取js中未定义的属性'0'
要解决该错误,请确保你仅在支持索引访问的值上访问索引,例如数组或字符串。
这是错误发生的示例
要解决次错误,请在访问索引之前将值初始化为特定数据类型,并使用if语句确定它是预期类型。
const fromDb = undefined
// 如果未定义,初始化空数组
const arr = fromDb || [];
console.log(arr[0]); // ✅undefined
// 如果未定义,初始化空字符串
const str = fromDb || '';
console.log(str[0]); // ✅undefined
// 在访问索引之前,检查是否是数组
if(Array.isArray(arr){
console.log(arr[0]);
} else {
console.log('arr is not an array');
}
// 在访问索引之前,检查是否是字符串
if(typeof str === 'string'){
console.log(str[0]);
} else {
console.log('str is not a string');
}
我们确保将arr和str变量的值初始化为逾期的类型,如果它们的值是假的,例如undefined。 如果左边的值是假的,使用短路运算符||(找true)允许我们提供一个备用值。然后,在访问索引之前,我们有条件地检查该值是否属于预期类型。
?.可选运算符
还可以使用可选运算符?.
const arr = undefined;
console.log(arr?.[0]); // ✅undefined
const str = undefined;
console.log(str?.[0]; // ✅undefined
选用可选运算符?.不会引发错误,而是短路返回null。
尝试访问嵌套数组的索引时,经常会出现此类错误。
我们声明的数组是空的,意味着会报错。
避免这个报错的一种简单办法是使用?.运算符
const arr = [];
console.log(arr?.[0]?.[0]); // ✅undefined
const hello = [['hello']];
console.log(hello?.[0]?.[0]); // ✅"hello"
此时不会报错啦!!
结论
出现此类bug时,不要慌。在访问索引之前,请确保正在访问索引的变量已经初始化为特定类型,例如数组或字符串。