我有这段代码:
var mydata = [];
$.each(divs, function(idx, val){
var dID = $(val).attr("id");
mydata[dID] = new Array();
mydata[dID].push({'newproperty':"newvalue"});
});
这给了我这样的结果:
25465: Array[1]
0: Object
newproperty: "newvalue"
__proto__: Object
length: 1
__proto__: Array[0]
我想这样:
25465: {
newproperty: "newvalue"
}
有什么想法吗?
答案 0 :(得分:4)
我想要这样
你已经投入了不必要的额外间接水平。
// Create a blank object
var mydata = {};
$.each(divs, function(idx, val){
var dID = $(val).attr("id");
// Add/overwrite a property on that object with the name from the
// variable dID, and the value being a new object with the properties
// shown -- I assume those properties are just examples, since as
// given they're identical on each pass...
mydata[dID] = {'newproperty':"newvalue"};
});
由于您未使用数组的Array
功能,请勿使用数组,只需使用对象({}
)即可。由于您的目标是让25465
等键直接引用对象,因此不要在数组/对象中创建数组,只需指定该键即可。