Javascript 在数组上调用forEach时出错
我在另一个forEach函数中遇到一个forEach问题:Javascript 在数组上调用forEach时出错,javascript,node.js,foreach,Javascript,Node.js,Foreach,我在另一个forEach函数中遇到一个forEach问题: results变量包含如下对象: { names: [ 'Someone', 'Someone else' ], emails: [ 'someone@someemail.com' 'something@somemail.com' ] } 我希望它展开所有数组并生成如下数组: [ {term: 'Someone', type: 'n
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
TypeError: Uncaught error: Cannot read property 'length' of undefined
我尝试使用迭代到长度的for循环,但它生成了另一个异常:
TypeError: Uncaught error: Cannot call method 'forEach' of undefined
TypeError: Uncaught error: Cannot read property 'length' of undefined
我认为这里的问题是,您可能会将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
});
});
}
});
试试,
console.log(key,arrTerms,Array.isArray(arrTerms))代码>代码本身对我来说很好(除了数组定义中缺少逗号)。results
实际上是什么样子的?它将typeOf打印为Object@ZeMoon抱歉,请尝试Array.isArray
。我编辑了comment@thefourtheyeArray.isArray(arrTerms)
返回true
因此,如果results[key]
是未定义的
,则attTerms
会发生什么如果找不到密钥,我们不想做任何事情,是吗?但您仍在调用arrTerms。forEach
即使results[key]
未定义。哦,请注意:)ty@ZeMoon:。.keys
,就像对象.keys
,将获取对象的所有属性名。因此,如果您有{foo:undefined}
,那么您将得到['foo']
。看来,毕竟,您没有发布对象的实际结构:P我想知道为什么没有捕获到它,因为您调用了console.log(keys)代码>已经存在。