首页 > 解决方案 > 如何使循环遍历枚举的每个项目并验证每个重复是否在正确的枚举中

问题描述

我想知道如何为枚举的每个项目创建一个重复的循环,并且仍然验证我在正确的枚举(索引)中

 for('for each or for in?') {
      if (list.names === enum) {
         console.log(enum)
    }
 }


enum = {
  JAMES: 'James',
  MARCO: 'Marco',
  Jane: 'Jane'
}

这段代码只是我想做的一个例子,对每种类型的枚举重复循环,然后验证我在第一个、第二个等,然后打印当前的枚举

  for (const newNames in enum) {
    console.log(newNames[enum])
  }

标签: javascriptnode.jsenums

解决方案


这是显示您的选项的快速片段,但这for...in就是您所需要的。

const obj = {
  JAMES: 'James',
  MARCO: 'Marco',
  Jane: 'Jane'
}

// for..in and access the value as normal - obj[key]
for (const key in obj) {
  console.log(`key: ${key}, obj[key]: ${obj[key]}`);
}

// for...of return an iterable of the object using Object.entries()
for (let [key, value] of Object.entries(obj)) {
  console.log(`key: ${key}, value: ${value}`);
}

// for...of turn the iterator into an array into an iterator and also get the indexes
for (let [i, [key, value]] of [...Object.entries(obj)].entries()) {
  console.log(`i: ${i}, key: ${key}, value: ${value}`);
}


推荐阅读