我想向“myObj”添加一个新属性,将其命名为“string1”并赋予其值“string2”,但是当我这样做时它返回“undefined:”
var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;
alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'
换句话说:我如何创建一个对象属性并赋予它存储在变量中的名称,而不是变量本身的名称?
最佳答案
有the dot notation and the bracket notation
myObj[a] = b;
关于javascript - 如何从 JavaScript 中的变量值创建对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2241875/