我有一个关联数组:
instrumentLookup: {
hh: {label: 'Hi Hat', type: 'hh'},
kd: {label: 'Kick Drum', type: 'kd'},
o1: {label: 'other1', type: 'o1'},
o2: {label: 'other2', type: 'o2'}
}
我认为这个结构还可以,但是可能还有更好的方法。
我正在尝试通过此函数从此列表中创建一个乐器,其中参数 addedInstrument
与标签的字符串相同,因此 hh
, kd
,o1
,....:
addInstrument: function(addedIntrument) {
console.warn(addedIntrument);
var newLabel = this.defaults.instrumentLookup.addedIntrument.label;
var newType = addedIntrument;
console.warn(newLabel + ' ' + newType)
// push it to the list
// this.unusedInstruments.push({label:newLabel, type:newType});
}
其中有几个问题,请随意回答任何或全部问题或提出替代方案:
- 当对象是关联数组的值时,如何访问对象属性?
- 我应该将其从关联数组更改为嵌套对象的数组[]{type: {other attrs}}吗?
最佳答案
您需要括号表示法来动态访问属性名称。
instrumentLookup[ addedIntrument ].label
关于javascript - 将对象值作为关联数组值访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17474699/