在JavaScript中,我创建了一个这样的对象:

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

如果直到运行时才确定属性名称,那么是否可以在初始创建该对象后向其添加更多属性?即。

var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to 
//my object?

当前回答

我知道这个问题的答案是完美的,但我也找到了另一种添加新属性的方法,并想与您分享:

你可以使用Object.defineProperty()函数

可以在Mozilla开发者网络上找到

例子:

var o = {}; // Creates a new object

// Example of an object property added with defineProperty with a data property descriptor
Object.defineProperty(o, "a", {value : 37,
                               writable : true,
                               enumerable : true,
                               configurable : true});
// 'a' property exists in the o object and its value is 37

// Example of an object property added with defineProperty with an accessor property descriptor
var bValue;
Object.defineProperty(o, "b", {get : function(){ return bValue; },
                               set : function(newValue){ bValue = newValue; },
                               enumerable : true,
                               configurable : true});
o.b = 38;
// 'b' property exists in the o object and its value is 38
// The value of o.b is now always identical to bValue, unless o.b is redefined

// You cannot try to mix both :
Object.defineProperty(o, "conflict", { value: 0x9f91102, 
                                       get: function() { return 0xdeadbeef; } });
// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors

其他回答

只是对上面的答案的补充。您可以定义一个函数来封装下面提到的defineProperty的复杂性。

var defineProp = function ( obj, key, value ){
  var config = {
    value: value,
    writable: true,
    enumerable: true,
    configurable: true
  };
  Object.defineProperty( obj, key, config );
};

//Call the method to add properties to any object
defineProp( data, "PropertyA",  1 );
defineProp( data, "PropertyB",  2 );
defineProp( data, "PropertyC",  3 );

参考:http://addyosmani.com/resources/essentialjsdesignpatterns/book/ # constructorpatternjavascript

Yes.

Var数据= { “PropertyA”:1、 “PropertyB”:2 “PropertyC”:3 }; data["PropertyD"] = 4; //对话框中包含4 警报(data.PropertyD); 警报(数据(“PropertyD”));

我知道这篇文章已经有几个答案,但我还没有看到其中有多个属性,它们在一个数组中。顺便说一下,这个解决方案是针对ES6的。

举例来说,假设我们有一个名为person的数组,其中包含对象:

 let Person = [{id:1, Name: "John"}, {id:2, Name: "Susan"}, {id:3, Name: "Jet"}]

因此,您可以添加具有相应值的属性。假设我们想要添加一个默认值为EN的Language。

Person.map((obj)=>({...obj,['Language']:"EN"}))

Person数组现在会变成这样:

Person = [{id:1, Name: "John", Language:"EN"}, 
{id:2, Name: "Susan", Language:"EN"}, {id:3, Name: "Jet", Language:"EN"}]

是的,这是可能的。假设:

var data = {
    'PropertyA': 1,
    'PropertyB': 2,
    'PropertyC': 3
};
var propertyName = "someProperty";
var propertyValue = "someValue";

:

data[propertyName] = propertyValue;

or

eval("data." + propertyName + " = '" + propertyValue + "'");

首选第一种方法。如果使用用户提供的值,Eval()有明显的安全问题,所以如果可以避免,就不要使用它,但知道它的存在以及它能做什么是值得的。

你可以参考:

alert(data.someProperty);

or

data(data["someProperty"]);

or

alert(data[propertyName]);

从包含对象的动态字符串名(例如object.subobject.property)进行访问的好方法

function ReadValue(varname)
{
    var v=varname.split(".");
    var o=window;
    if(!v.length)
        return undefined;
    for(var i=0;i<v.length-1;i++)
        o=o[v[i]];
    return o[v[v.length-1]];
}

function AssignValue(varname,value)
{
    var v=varname.split(".");
    var o=window;
    if(!v.length)
        return;
    for(var i=0;i<v.length-1;i++)
        o=o[v[i]];
    o[v[v.length-1]]=value;
}

例子:

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

Eval适用于读值,但写值有点难。

一个更高级的版本(如果不存在就创建子类,并且允许对象而不是全局变量)

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<v.length-1;i++)
    {
        if(o[v[i]]===null || typeof(o[v[i]])==="undefined") 
            o[v[i]]={};
        o=o[v[i]];
    }
    if(typeof(o[v[v.length-1]])==="undefined")    
        return undefined;
    else    
        return o[v[v.length-1]];
}

function AssignValue(varname,value,o=window)
{
    if(typeof(varname)==="undefined" || typeof(o)==="undefined" || o===null)
        return;
    var v=varname.split(".");
    if(!v.length)
        return;
    for(var i=0;i<v.length-1;i++)
    {
        if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
            o[v[i]]={};
        o=o[v[i]];
    }
    o[v[v.length-1]]=value;
}

例子:

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

这与o.object。subobject。property相同