const arr = [];
// ⛔️ Cannot read properties of undefined (reading 'name')
console.log(arr[0].name); // ❌ Bad
console.log(arr[0]?.name); // ✅ Good
console.log(arr[0] && arr[0].name); // ✅ Good
JS 中括号取值的undefined 判断
2 min read
const arr = [];
// ⛔️ Cannot read properties of undefined (reading 'name')
console.log(arr[0].name); // ❌ Bad
console.log(arr[0]?.name); // ✅ Good
console.log(arr[0] && arr[0].name); // ✅ Good