我有以下代码(函数名为group),它通过关联数组中的某个属性(属于person对象)将人对象从人数组分组到数组中。因此,人员组(数组)通过作为属性值的键放入生成的关联数组中。例如,我们创建了一个数组,并通过lastname =' Bunny'创建并存储到最终数组中:来自姓氏为Bunny的四个人。问题是,当我在循环中尝试显示我在每个组末尾的对象时,会出现一个未定义的对象。如果我使用for循环遍历数组/对象,则不会发生这种情况。但我不能用关联数组来做,因为它没有索引。我想知道为什么console.log显示一个未定义的值,它可以用原型做些什么吗?感谢。
persons=[
{ firstname: 'Funny', lastname: 'Bunny', age: 32 },
{ firstname: 'Little', lastname: 'Bunny', age: 12 },
{ firstname: 'Buggs', lastname: 'Bunny', age: 42 },
{ firstname: 'Ivan', lastname: 'Petrov', age: 52 },
{ firstname: 'Honey', lastname: 'Bunny', age: 22 },
{ firstname: 'John', lastname: 'Doe', age: 32 },
{ firstname: 'Mike', lastname: 'Doe', age: 22 }
];
function group(personsArray, groupType) {
var associativeArray = {};
for (var i in personsArray) {
if (!associativeArray[personsArray[i][groupType]]) {
associativeArray[personsArray[i][groupType]] = [];
}
associativeArray[personsArray[i][groupType]].push(personsArray[i]);
}
return associativeArray;
}
var res = group(persons, 'lastname');
for (var item in res) {
console.log('GROUP: ' + item);
for (var i = 0; i < res[item].length; i++) {
console.log((res[item])[i].firstname);
}
}
Output:
GROUP: Bunny
Funny
Little
Buggs
Honey
GROUP: Petrov
Ivan
GROUP: Doe
John
Mike
GROUP: undefined
undefined
答案 0 :(得分:2)
阅读Why is using "for...in" with array iteration a bad idea?。如果您的persons
数组中有任何其他可枚举的属性,例如继承自Array.prototype
,然后它还会对其姓氏undefined
进行分组。