0

What I'm trying to achieve is the following structure for an object. Note that all properties values are constant strings:

ObjA
    ObjB
        prop1
        prop2
        prop3
    ObjC
        prop4
        prop5
    .
    .
    .

So shoud it be possible to access the properties value using the following sintax:

alert(ObjA.ObjC.pro4);

So far, I've tried something like the following without success.

    var csi = new Object();
    var cao98 = new Object();
    csi.cao98="";
    csi.cao98.rgi = "NRRGILIG";
    alert (csi.cao98.rgi);

Is it possible? I do not want to get to far on this issue since there's a lot of discussion on this theme.

4

3 回答 3

2

If you just want plain objects, you can write that all into one expression using the literal syntax for objects:

var ObjA = {
        ObjB: {
            prop1: 'hello',
            prop2: 'howdy'
        },
        ObjC: {
            prop1: 'hi',
            prop2: 'world'
        }
    }
}

console.log(ObjA.ObjB.prop1 + ' ' + ObjA.ObjC.prop2);
于 2012-12-05T14:02:51.193 回答
2

在您的第三行,您将一个空字符串分配给cao98您的csi对象的属性。

我认为您的意思是:

var csi = new Object();
var cao98 = new Object();
csi.cao98=cao98;
csi.cao98.rgi = "NRRGILIG";
alert (csi.cao98.rgi);

如果您只是像这样逐字定义对象,则可以改用对象文字语法:

var csi = {
    cao98: {
        rgi: "NRRGILIG"
    }
};

alert (csi.cao98.rgi);

最佳方法取决于您使用对象的上下文。

于 2012-12-05T14:01:30.320 回答
0

try

    var csi = {
        cao: {
            rgi: 'NRRGILIG'
        }
    };
于 2012-12-05T14:04:05.047 回答