避免“无法读取”属性'获取'的未定义错误

Avoiding a Cannot read property 'get' of undefined error

本文关键字:获取 错误 未定义 属性 读取 无法读取 避免      更新时间:2023-12-16

当我运行代码时,控制台会打印出一条错误消息Cannot read property 'get' of undefined error。我以为if语句可以避免这种情况,但到目前为止还不是运气。这是我的代码

   if (records[0].get('StatusString') !== 'undefined') {
              creativeStatus = records[0].get('StatusString');
}

如果您的array未定义,它将失败。请将if语句扩展到以下

if (records && records[0] && records[0].get('StatusString') !== 'undefined') {
    creativeStatus = records[0].get('StatusString');
}
if (typeof (records && records[0] && records[0].get) !== 'undefined'){
   creativeStatus = records[0].get('StatusString');
}

records[0]未定义。试着在它周围进行if检查以发现错误。

if (records[0] !== 'undefined') {
  creativeStatus = records[0].get('StatusString');
}