【问题标题】:Checking defined item in enum [duplicate]检查枚举中定义的项目[重复]
【发布时间】: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。

这是实际的enum 对象:

这是实际的功能代码:

更新 2: 我通过在花括号中导入枚举解决了这个问题——见下文:

import {calendarEvents} from '../../enums/calendarEvents';

【问题讨论】:

  • 所以if(uiElementAttributes.hasOwnProperty(id)){ /*it exists*/}

标签: javascript enums


【解决方案1】:

在这种特殊情况下,您可以访问该属性,如果结果为假,则使用默认属性99

const getAttributes = id => uiElementAttributes[id] || uiElementAttributes[99];

否则,您可以使用in operator,或建议的Object#hasOwnProperty

【讨论】:

  • 我正在使用这个建议的解决方案,它看起来很简单,但我遇到了一个错误。请参阅我添加到原始帖子中的更新。
  • 取决于数据结构,在图片上是看不到的。
  • 刚刚用enum 对象的屏幕截图更新了原始帖子。
  • 在实际代码中,我的默认值将来自对象0。
  • 我解决了。请参阅更新 2。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2010-10-25
  • 1970-01-01
  • 2017-11-30
  • 2014-09-19
  • 1970-01-01
  • 2013-10-06
  • 2013-03-12
  • 1970-01-01
相关资源
最近更新 更多