简体   繁体   English

对象的javascript数组成员

[英]javascript array member of object

I would like to create in javascript an object that contains an array of other objects. 我想在javascript中创建一个包含其他对象数组的对象。 ie

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 . 我想topObj.x是数组xobj

I am getting: 我正进入(状态:

Uncaught TypeError: Cannot set property 'd' of undefined 未捕获的TypeError:无法设置未定义的属性“ d”

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

topObj.x.push(xobj);

if you wanted just the values in the xobj to be appended to the array I would create something like this 如果您只想将xobj中的值附加到数组中,则可以创建如下内容

for (prop in xobj) {
    topObj.x.push(xobj[prop])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM