从String中引用Object

her*_*ann 3 javascript arrays object

我有以下一段完美的代码.

However, my list of items below is going to grow to become tens of objects and I want to know if it is possible to remove the switch clause and have something smaller and fewer lines of code.

the 'type' argument is the type of the array, viewport, container, gridpanel, etc. and the 'component' argument is the object itself which goes in the array.

viewport: {},
container: {},
gridpanel: {},
panel: {},
treepanel: {},
window: {},
button: {},

add: function (component, type) {

    switch (component.getType() != undefined ? component.getType() : type) {
        case 'container':
            this.container[component.getId()] = component;
            break;
        case 'gridpanel':
            this.gridpanel[component.getId()] = component;
            break;
        case 'panel':
            this.panel[component.getId()] = component;
            break;
        case 'treepanel':
            this.treepanel[component.getId()] = component;
            break;
        case 'viewport':
            this.viewport[component.getId()] = component;
            break;
        case 'window':
            this.window[component.getId()] = component;
            break;
        case 'button':
            this.button[component.getId()] = component;
            break;
        default:
            break;
    }
},
Run Code Online (Sandbox Code Playgroud)

Fré*_*idi 7

您可以使用括号表示法来引用组件类型:

add: function(component, type) {
    var componentType = component.getType() || type;
    this[componentType][component.getId()] = component;
}
Run Code Online (Sandbox Code Playgroud)