如何在Node.js中声明和使用map / dictionary?

时间:2018-08-31 04:34:31

标签: javascript node.js

可能是node.js这样的东西吗?

var LANGUAGE = {
    LANG1: 'Language 1',
    LANG2 'Language 2'
}

var TARGET = {
    TARG1: { LANG1: 'target 1 in lang 1', LANG2: 'target 1 in lang 2' },
    TARG2: { LANG1: 'target 2 in lang 1', LANG2: 'target 2 in lang 2' }
}

var ACTION = {
    ACT1: { LANG1: 'action 1 in lang 1', LANG2: 'action 1 in lang 2' },
    ACT2: { LANG1: 'action 2 in lang 1', LANG2: 'action 2 in lang 2' }  
}


var currentLanguage = LANGUAGE.LANG1;
var currentTarget = TARGET.TARG2;
var currentAction = ACTION.ACT1;

var message = 'You have successfully performed ' + currentAction[currentLanguage] + ' on ' + currentTarget[currentLanguage];

console.log(message);

我不确定上面的来源中 LANGUAGE.LANG1 TARG1之间是否存在任何关系:{LANG1 :等...

========在VSCode中运行此结果后更新结果========

You have successfully performed undefined on undefined

3 个答案:

答案 0 :(得分:1)

您应该阅读有关javascript点和括号符号的更多信息。
在您的情况下,currentAction[currentLanguage]将是currentAction['Language 1'],并且'Language 1'对象中的键currentAction没有值(等于{ LANG1: 'action 1 in lang 1', LANG2: 'action 1 in lang 2' }
currentAction['LANG1']currentAction.LANG1将返回您想要的值。

ES6具有动态键语法,您可以在其中使用变量作为对象常量中的键
{ [LANGUAGE.LANG1]: 'some value'}

答案 1 :(得分:1)

当然可以。您的问题是LANGUAGE对象中的值必须是其他对象中的键,所以...

var LANGUAGE = {
    LANG1: 'LANG1',
    LANG2: 'LANG1'
}

(您还缺少发布代码中的第二个冒号。)

使用以上打印...

  

您已成功对语言1中的目标2执行了语言1中的操作1

答案 2 :(得分:0)

多亏了31piy,

我找到了一种工作方式。也许这不是最好的。

var LANGUAGE = {
    LANG1: 'Language 1',
    LANG2: 'Language 2'
}

var TARGET = {
    TARG1: new Map(),
    TARG2: new Map() 
}

var ACTION = {
    ACT1: new Map(),
    ACT2: new Map() 
}

TARGET.TARG1.set(LANGUAGE.LANG1, 'target 1 in lang 1');
TARGET.TARG1.set(LANGUAGE.LANG2, 'target 1 in lang 2');
TARGET.TARG2.set(LANGUAGE.LANG1, 'target 2 in lang 1');
TARGET.TARG2.set(LANGUAGE.LANG2, 'target 2 in lang 2');

ACTION.ACT1.set(LANGUAGE.LANG1, 'action 1 in lang 1');
ACTION.ACT1.set(LANGUAGE.LANG2, 'action 1 in lang 2');
ACTION.ACT2.set(LANGUAGE.LANG1, 'action 2 in lang 1');
ACTION.ACT2.set(LANGUAGE.LANG2, 'action 2 in lang 2');

var currentLanguage = LANGUAGE.LANG1;
var currentTarget = TARGET.TARG2;
var currentAction = ACTION.ACT1;

var message = 'You have successfully performed ' + currentAction.get(currentLanguage) + ' on ' + currentTarget.get(currentLanguage);

console.log(message);

结果与预期的一样:)

You have successfully performed action 1 in lang 1 on target 2 in lang 1