我无法理解为什么我的控制台给了我这个:
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);
}
});
console.log的结果是:
undefined
0
我缺少什么?
答案 0 :(得分:1)
不要认为您正在显示弹出result
对象的相关代码。
假设result
对象应该填充在这里
months.forEach(function (m){
if ( !result )
{
result = {};
}
if ( !result.GulAvformning )
{
result.GulAvformning = {};
}
if (! result.GulAvformning[m]) {
result.GulAvformning[m] = 0;
}
});