简体   繁体   English

JS / ES6在map.get中引用一个常量

[英]JS/ES6 Reference a constant in map.get

Is it possible to use a constant instead of a key from a map as long as the constant's value equals a key from the map? 只要常量的值等于映射中的键,是否可以使用常量而不是映射中的键?

const myColor = 'dark';
const myMap = new Map();

myMap.set('dark', {
  primary: '#000',
});

const myValues: {
  first: myMap.get(myColor).primary,
}
                   ^ This should output to 'dark' and access the primary key.

Is it possible to use a constant instead of a key from a map as long as the constant's value equals a key from the map? 只要常量的值等于映射中的键,是否可以使用常量而不是映射中的键?

Yes, you can use any variable as the key as long as its value is === to the original key. 是的,您可以使用任何变量作为键,只要其值等于原始键=== const or no const does not make a difference for a Map key. const或no const不会对Map键产生影响。


Also, in your myValues declaration, it should be this: 另外,在myValues声明中,应为:

const myValues = {
  first: myMap.get(myColor).primary,
}

where you use = instead of : . 使用=而不是:

yes, your only problem is that your syntax is off. 是的,您唯一的问题是语法已关闭。

const myColor = 'dark';
const myMap = new Map();

myMap.set('dark', {
  primary: '#000',
});

const myValues = {
  first: myMap.get(myColor).primary,
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM