8

我正在尝试这样做:

var KEYS = {} ;

KEYS.PHONE_TYPE = 'phone-type';
KEYS.AGENT_TYPE = 'agent-type';

var myAppConfig = {
    ...
    iconMap : { 
        KEYS.PHONE_TYPE : 'icon-phone', 
        KEYS.AGENT_TYPE : 'icon-headphones'
    };
    ...
};

但它失败了,并显示一条消息:Expected ':' and instead saw '.'.

如何使用间接(非文字)键名初始化对象?

需要明确的是,我想要的结果是:

{
    'phone-type' : 'icon-phone',
    'agent-type' : 'icon-headphones'
}
4

2 回答 2

12

如果你使用 ES6(或类似 Babel/browserify 的东西),你可以这样写:

iconMap : { 
    [KEYS.PHONE_TYPE] : 'icon-phone', 
    [KEYS.AGENT_TYPE] : 'icon-headphones'
};
于 2016-08-25T14:30:43.147 回答
7

You would have to add those properties separately using bracket notation:

var myAppConfig = {
    ...
    iconMap : { }
    ...
};

myAppConfig.iconMap[ KEYS.PHONE_TYPE ] = 'icon-phone';
myAppConfig.iconMap[ KEYS.AGENT_TYPE ] = 'icon-headphones';
于 2013-07-24T11:25:34.930 回答