我正在遍历这个对象:
var object = {
first : {
child1 : 'test1',
child2 : 'test2'
},
second : {
child1 : 'test3',
child2 : 'test4'
},
first : {
child1 : 'test5',
child2 : 'test6!'
}
};有了这个:
for(var attribute in object){
alert(attribute + " : " + object[attribute]);
}首先,它似乎是有效的,但它只迭代具有唯一名称的子对象,因此跳过了第一个带有:first的对象。
那么迭代整个对象的正确解决方案是什么呢?
发布于 2011-06-11 01:52:55
JavaScript对象是关联映射,不能有多个具有相同键(名称)的值。您的数据不能具有该结构。
另一种选择可能是键-值对数组。
var object = [
["first", {
child1 : 'test1',
child2 : 'test2'
}],
["second", {
child1 : 'test3',
child2 : 'test4'
}],
["first", {
child1 : 'test5',
child2 : 'test6!'
}]
];
var i, attribute, value;
for (i = 0; i < object.length; i++) {
attribute = object[i][0];
value = object[i][1];
alert("" + attribute + " = " + value);
}发布于 2011-06-11 01:54:01
迭代没有问题,对象有问题。名为first的第二个属性将替换第一个first,并将其擦除。
谁先上场?
https://stackoverflow.com/questions/6310214
复制相似问题