【发布时间】:2017-07-18 17:48:03
【问题描述】:
我有一个枚举,其中存储了一些如下所示的 UI 元素值:
const uiElementAttributes = {
1: {
id: 1,
color: 'red',
icon: 'icon-something.png'
},
2: {
id: 2,
color: 'yellow',
icon: 'icon-something-else.png'
},
3: {
id: 3,
color: 'blue',
icon: 'icon-this-item.png'
},
99: {
id: 99,
color: 'black',
icon: 'icon-black.png'
}
};
我有一个函数,它将根据传递给我的函数的 id 从枚举中返回正确的对象。我的问题是如何检查枚举中是否定义了值?
函数如下:
const getAttributes (id) => {
// How do I check to see if the id is in the enum?
if(checkIfIdIsInEnum) {
return uiElementAttributes[id];
} else {
return uiElementAttributes[99];
}
};
更新:我正在尝试建议的答案。它看起来确实很简单,但看起来当 webpack 将我的代码转换为 vanilla JS 时,它会在我的 enum 的末尾添加 default,即 undefined。知道是什么原因造成的——见下文?如您所见,我传递的id 值是1,因此它应该能够在我的枚举对象中找到值1。
更新 2: 我通过在花括号中导入枚举解决了这个问题——见下文:
import {calendarEvents} from '../../enums/calendarEvents';
【问题讨论】:
-
所以
if(uiElementAttributes.hasOwnProperty(id)){ /*it exists*/}
标签: javascript enums