Cannot read properties of undefined (reading ‘0‘) - 解决使用嵌套数组时的错误

在访问不存在的索引处的嵌套数组然后访问索引处的值时,也会发生 Cannot read properties of undefined (reading '0')

const arr = [
  ['a', 'b'],
  ['c', 'd'],
];

// ⛔️ TypeError: Cannot read properties of undefined (reading '0')
console.log(arr[2][0]);

解决

使用**可选链操作符( ?. )**

const arr = [
  ['a', 'b'],
  ['c', 'd'],
];

console.log(arr?.[0]); // ️ ['a', 'b']
console.log(arr?.[0]?.[0]); // ️ a
console.log(arr?.[0]?.[0]?.[1]); // ️ undefined
console.log(arr?.[0]?.[1]?.[0]?.[0]); // ️ b

你可能感兴趣的:(javascripts,javascript,前端)