2015-04-01 52 views
0

我越来越anoter的forEach函数内的问题的forEach:错误调用foreach所阵列

results变量包含类似于对象:

{ 
    names: [ 
     'Someone', 
     'Someone else' 
    ], 
    emails: [ 
     '[email protected]' 
     '[email protected]' 
    ] 
} 

我希望它放松所有的阵列和导致数组是这样的:

[ 
    {term: 'Someone', type: 'names'}, 
    ... 
] 

这里是我的代码:

var keys = _.keys(results); 

console.log(keys); 

var finalResult = []; 

keys.forEach(function (key) { 

    var arrTerms = results[key]; 

    console.log(key, arrTerms); //arrTerms prints fine 

    arrTerms.forEach(function (term) { //This line throws an exception 

     finalResult.push({ 
      term: term, 
      type: key 
     }); 
    }); 

}); 

到的forEach嵌套调用抛出以下异常:

TypeError: Uncaught error: Cannot call method 'forEach' of undefined 

我尝试使用for循环与迭代直到长,但它产生的另一个例外:

TypeError: Uncaught error: Cannot read property 'length' of undefined 
+0

尝试,'的console.log(键,arrTerms,Array.isArray(arrTerms));' – thefourtheye 2015-04-01 15:59:07

+0

,因为它是我工作正常(除了丢失的阵列中一个逗号的代码定义)。 “结果”究竟是什么样子? – 2015-04-01 15:59:32

+0

它将typeOf打印为对象 – ZeMoon 2015-04-01 15:59:35

回答

1

我觉得这里的问题是你可以为你的arrTerms赋值undefined(当result [key]返回undefined时,你会得到一个不包含在你的对象中的key)。试着这样做:

var keys = _.keys(results); 

console.log(keys); 

var finalResult = []; 

keys.forEach(function (key) { 
    if(results[key] != undefined){ 
    var arrTerms = results[key]; 

    arrTerms.forEach(function (term) { //This line throws an exception 
     console.log(key, arrTerms); //arrTerms prints fine 
     finalResult.push({ 
      term: term, 
      type: key 
     }); 
    }); 
    } 
}); 
+0

那么,如果'[key]'是'undefined','attTerms'会发生什么? – 2015-04-01 16:08:31

+0

没什么。 :)如果我们找不到钥匙,我们不想做任何事情,是吗? – OddDev 2015-04-01 16:08:55

+0

但是,即使'results [key]'未定义,你仍然在调用'arrTerms.forEach'。 – 2015-04-01 16:09:15