Is it possible to add dynamically named properties to JavaScript object?

后端 未结 19 1517
攒了一身酷
攒了一身酷 2020-11-21 05:39

In JavaScript, I\'ve created an object like so:

var data = {
    \'PropertyA\': 1,
    \'PropertyB\': 2,
    \'PropertyC\': 3
};

Is it poss

19条回答
  •  失恋的感觉
    2020-11-21 06:14

    A nice way to access from dynamic string names that contain objects (for example object.subobject.property)

    function ReadValue(varname)
    {
        var v=varname.split(".");
        var o=window;
        if(!v.length)
            return undefined;
        for(var i=0;i

    Example:

    ReadValue("object.subobject.property");
    WriteValue("object.subobject.property",5);
    

    eval works for read value, but write value is a bit harder.

    A more advanced version (Create subclasses if they dont exists, and allows objects instead of global variables)

    function ReadValue(varname,o=window)
    {
        if(typeof(varname)==="undefined" || typeof(o)==="undefined" || o===null)
            return undefined;
        var v=varname.split(".");
        if(!v.length)
            return undefined;
        for(var i=0;i

    Example:

    ReadValue("object.subobject.property",o);
    WriteValue("object.subobject.property",5,o);
    

    This is the same that o.object.subobject.property

提交回复
热议问题