javascript 在数组上调用 forEach 时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29395410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error calling forEach on array
提问by ZeMoon
I am getting a problem forEach within anoter forEach function:
我在另一个 forEach 函数中遇到了 forEach 问题:
The results
variable contains an object like:
该results
变量包含一个对象,如:
{
names: [
'Someone',
'Someone else'
],
emails: [
'[email protected]'
'[email protected]'
]
}
I want it to unwind all the arrays and result in an array like this:
我希望它展开所有数组并产生这样的数组:
[
{term: 'Someone', type: 'names'},
...
]
Here is my code:
这是我的代码:
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
});
});
});
The nested call to forEach throws the following exception:
对 forEach 的嵌套调用会引发以下异常:
TypeError: Uncaught error: Cannot call method 'forEach' of undefined
I tried using a for loop with iteration till length, but it generated another exception:
我尝试使用迭代直到长度的 for 循环,但它产生了另一个异常:
TypeError: Uncaught error: Cannot read property 'length' of undefined
回答by OddDev
I think the problem here is that you may assign undefined to your arrTerms (when results[key] returns undefined cause you take a key which isn't contained in your object). Try to do this:
我认为这里的问题是您可能将 undefined 分配给您的 arrTerms (当 results[key] 返回 undefined 时,您会使用一个不包含在您的对象中的键)。尝试这样做:
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
});
});
}
});