【发布时间】:2015-04-01 15:55:47
【问题描述】:
我在另一个 forEach 函数中遇到了问题:
results 变量包含如下对象:
{
names: [
'Someone',
'Someone else'
],
emails: [
'someone@someemail.com'
'something@somemail.com'
]
}
我希望它展开所有数组并生成这样的数组:
[
{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
【问题讨论】:
-
试试,
console.log(key, arrTerms, Array.isArray(arrTerms)); -
代码对我来说很好用(除了您在数组定义中缺少逗号)。
results到底长什么样子? -
它将 typeOf 打印为 Object
-
@ZeMoon 对不起,试试
Array.isArray。我编辑了评论 -
@thefourtheye
Array.isArray(arrTerms)返回true
标签: javascript node.js foreach