无法读取未定义的属性“jan”

Cannot read property 'jan' of undefined

本文关键字:jan 属性 读取 未定义      更新时间:2023-09-26

我不明白为什么我的控制台给我这个:

Uncaught TypeError: Cannot read property 'jan' of undefined

此代码的功能是将 var 设置为 0,如果它是"未定义的"。

//Set months to loop/look for
var months = ["jan","feb","mar","apr","maj","jun","jul","aug","sep","okt","nov","dec"];
//GUL Loop threw result and create vars for each month
months.forEach(function (m){
  if (! result.GulAvformning[m]) {
    result.GulAvformning[m] = {};
    result.GulAvformning[m] = 0;
  }
});

我有另一个代码,它没有抱怨这一点:

//BLÅ Loop threw result and create vars for each month
months.forEach(function (m){
  if (! result.BlåAvformning[m]) { console.log(result.BlåAvformning.jan);
    result.BlåAvformning[m] = {};
    result.BlåAvformning[m] = 0; console.log(result.BlåAvformning.jan);
  }
});

控制台的结果.log为:

undefined
0

我错过了什么?

不要认为您正在显示弹出result对象的相关代码。

假设result对象应该填充在此处

months.forEach(function (m){
  if ( !result )
  {
    result = {};
  }
  if ( !result.GulAvformning )
  {
     result.GulAvformning = {};
  }
  if (! result.GulAvformning[m]) {
    result.GulAvformning[m] = 0;
  }
});