【问题标题】:How I create an enum from an array?如何从数组创建枚举?
【发布时间】:2020-04-13 10:16:01
【问题描述】:

我需要像这样生成enumErrorList

Errors={
    none:0,
    subject:1,
    content:2,
    sender:4,
    recipient:8
}

来自这样的数组

let errors=[
        'none',
        'subject',
        'content',
        'sender',
        'recipient'
]

但很抱歉我对枚举不是很熟悉。

【问题讨论】:

    标签: javascript arrays enums


    【解决方案1】:

    如下使用Object.entriesObject.fromEntries

    let errors=[
            'none',
            'subject',
            'content',
            'sender',
            'recipient'
    ]
    
    let Errors = Object.fromEntries(Object.entries(errors).map(([a,b]) => [b, ((1<<a)>>1)]));
    console.log(Errors)

    【讨论】:

    • 好的,|0 做得很好。我绞尽脑汁想弄清楚如何通过按位运算来实现它,因为1 &lt;&lt; index 是正确的方法……除了0。由于某种原因,我完全忘记了我忽略了我可以只使用两个操作。你的/2 让我想起了这一点,所以它最终点击了1 &lt;&lt; index &gt;&gt; 1 只设置了n-1 位,而index = 0 恰好没有位。
    • d'oh ...当然>:p - 我有一个老年人的时刻:p
    • 别担心,我也是。我知道那种感觉:D
    【解决方案2】:

    您可以获取数组,然后使用Array#reduceObject.assign 在那里生成一个对象:

    • 键是数组中的项。
    • 值从零开始按 2 的幂增长。

    let errors=[
            'none',
            'subject',
            'content',
            'sender',
            'recipient'
    ]
    
    const Errors = errors.reduce(
      (acc, item, index) => Object
        .assign(
          acc, 
          {[item]: Math.floor(2 ** (index - 1))}
        ), 
      {}
    )
    
    console.log(Errors)

    或通过位算术仅产生 2 的幂,方法是在 n=0 时设置位 n-10 开头:

    let errors=[
            'none',
            'subject',
            'content',
            'sender',
            'recipient'
    ]
    
    const Errors = errors.reduce(
      (acc, item, index) => Object
        .assign(
          acc, 
          {[item]: (1 << index) >> 1}
        ), 
      {}
    )
    
    console.log(Errors)

    【讨论】:

    • 感谢您的回复非常友好和详尽
    猜你喜欢
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    相关资源
    最近更新 更多