0

I would like to create in javascript an object that contains an array of other objects. i.e.

var xobj = {
    d: 0,
    e: 0,
    f: 0
};

var topObj = {
    x: [],
    a: 0,
    b: 0,
    c: 0
};

topObj.x[0].d = 1;
topObj.x[0].e = 2;
var xx = topObj.x[0].d + topObj.x[0].e;

console.log( xx );

I would like topObj.x to be an array of xobj.

I am getting:

Uncaught TypeError: Cannot set property 'd' of undefined

4

2 回答 2

3

您可以这样做,但您必须使用对象 (xobj) 的实例填充数组:

topObj.x.push(xobj);
于 2013-05-14T04:51:05.273 回答
0

如果您只想将 xobj 中的值附加到数组中,我将创建类似这样的内容

for (prop in xobj) {
    topObj.x.push(xobj[prop])
}
于 2013-05-14T04:59:44.553 回答