Javascript 如何向JS/ExtJS对象添加属性(动态命名)?
考虑以下要求: 假设我有:var sampleObj={} 我想向该对象添加一些属性+值。e、 g.合成obj应为:Javascript 如何向JS/ExtJS对象添加属性(动态命名)?,javascript,extjs,javascript-objects,Javascript,Extjs,Javascript Objects,考虑以下要求: 假设我有:var sampleObj={} 我想向该对象添加一些属性+值。e、 g.合成obj应为: sampleObj = { 'att1' : 'value1', 'att2' : 'value2', 'att3' : 'value3' } 现在我可以通过直接设置sampleObj.att1='value1'来轻松实现这一点,依此类推 但问题是我动态地获取属性名称。假设名称在某些字符串变量中,例如attName='att5'
sampleObj =
{
'att1' : 'value1',
'att2' : 'value2',
'att3' : 'value3'
}
现在我可以通过直接设置sampleObj.att1='value1'来轻松实现这一点,依此类推
但问题是我动态地获取属性名称。假设名称在某些字符串变量中,例如attName='att5'
sampleObj.set/addattName,“value”;不起作用
如果像sampleObj.attName='value'一样尝试,它会添加'attName'作为属性
我想要的是类似sampleObj的东西。${attName}='value'
如何执行此操作?您需要使用访问具有变量名的属性:
sampleObj[attName] = 'value';
您需要使用访问变量名为的属性:
sampleObj[attName] = 'value';
你应该能够使用。您还应该能够使用标准数组类型赋值,例如sampleObj['attr1']='value'
因此,在这种情况下,您可以执行以下操作:
var sampleObj =
{
'att1' : 'value1',
'att2' : 'value2',
'att3' : 'value3'
}
var panel = Ext.create('Ext.panel.Panel');
Ext.apply(panel, sampleObj);
在浏览器控制台firefox中测试:
var sampleObj =
{
'att1' : 'value1',
'att2' : 'value2',
'att3' : 'value3'
}
sampleObj.att4 = 'value4';
sampleObj['att5'] = 'value5';
console.log(sampleObj);
产生了以下输出:
att1" "value1"
att2" "value2"
att3: "value3"
att4: "value4"
att5: "value5"
所以以上所有方法对我都有效你应该能够使用。您还应该能够使用标准数组类型赋值,例如sampleObj['attr1']='value'
因此,在这种情况下,您可以执行以下操作:
var sampleObj =
{
'att1' : 'value1',
'att2' : 'value2',
'att3' : 'value3'
}
var panel = Ext.create('Ext.panel.Panel');
Ext.apply(panel, sampleObj);
在浏览器控制台firefox中测试:
var sampleObj =
{
'att1' : 'value1',
'att2' : 'value2',
'att3' : 'value3'
}
sampleObj.att4 = 'value4';
sampleObj['att5'] = 'value5';
console.log(sampleObj);
产生了以下输出:
att1" "value1"
att2" "value2"
att3: "value3"
att4: "value4"
att5: "value5"
所以以上所有方法对我都有效谢谢!我不知道这个语法。没想到这么简单…:-谢谢我不知道这个语法。没想到这么简单…:-