2015-04-01 56 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