我不是很确定我完全跟着你,但你的意思是这样吗?
var data = [Object, Object, Object];
var artikelen = [];
for(var i=0; i
if( !artikelen[data[i].category])
artikelen[data[i].category] = new Array();
if( !artikelen[data[i].category][data[i].type] )
artikelen[data[i].category][data[i].type] = new Array();
artikelen[data[i].category][data[i].type].push(data[i]);
}更完整的例子:(还要注意我把类别而不是类别,如果需要改变)。
var obj1 = new Object();
obj1.category = 1;
obj1.type = 2;
obj1.id = 1;
var obj2 = new Object();
obj2.category = 1;
obj2.type = 2;
obj2.id = 2;
var obj3 = new Object();
obj3.category = 2;
obj3.type = 4;
obj3.id = 3;
// Array containing all the objects from the server
// looks like this
var data = [obj1, obj2, obj3];
var artikelen = [];
for(var i=0; i
if( !artikelen[data[i].category])
artikelen[data[i].category] = new Array();
if( !artikelen[data[i].category][data[i].type] )
artikelen[data[i].category][data[i].type] = new Array();
artikelen[data[i].category][data[i].type].push(data[i]);
}
alert( artikelen[1][2] ); // expected [object], [object]
alert( artikelen[1][2][0].type ); // expected 2
要从这种方法中剔除的关键事项:
检查密钥是否存在
如果没有,请创建
.push可用于javascript数组以将项目添加到数组
使用字符串作为对象的类型:
var obj1 = new Object();
obj1.category = 1;
obj1.type = "hello hello";
obj1.id = 1;
var obj2 = new Object();
obj2.category = 1;
obj2.type = 2;
obj2.id = 2;
var obj3 = new Object();
obj3.category = 2;
obj3.type = 4;
obj3.id = 3;
// Array containing all the objects from the server
// looks like this
var data = [obj1, obj2, obj3];
var artikelen = [];
for(var i=0; i
if( !artikelen[data[i].category])
artikelen[data[i].category] = new Array();
if( !artikelen[data[i].category][data[i].type] )
artikelen[data[i].category][data[i].type] = new Array();
artikelen[data[i].category][data[i].type].push(data[i]);
}
alert( artikelen[1][2] ); // expected [object], [object]
alert( artikelen[1]["hello hello"][0].type ); // expected "hello hello"编辑
我给了它一些,思考并且在阅读this之后,事实证明Javascript中的arrays不适合用作关联数组(如在PHP中)。实际上,您只是向对象添加属性。因此,将其改为object则更好。例如,以下内容:
var obj1 = new Object();
obj1.category = 1;
obj1.type = "hello hello";
obj1.id = 1;
var obj2 = new Object();
obj2.category = 1;
obj2.type = 2;
obj2.id = 2;
var obj3 = new Object();
obj3.category = 2;
obj3.type = 4;
obj3.id = 3;
// Array containing all the objects from the server
// looks like this
var data = [obj1, obj2, obj3];
var artikelen = [];
for(var i=0; i
if( !artikelen[data[i].category])
artikelen[data[i].category] = new Object();
if( !artikelen[data[i].category][data[i].type] )
artikelen[data[i].category][data[i].type] = new Object();
artikelen[data[i].category][data[i].type] = (data[i]);
}
console.dir( artikelen ); // if using a debugger with console, gives detailed info此外,如果使用调试器,例如Firefox中的Firebug,您可以使用console.dir函数查看详细信息。