javascript - 如何使循环遍历枚举的每个项目并验证每个重复是否在正确的枚举中
问题描述
我想知道如何为枚举的每个项目创建一个重复的循环,并且仍然验证我在正确的枚举(索引)中
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])
}
解决方案
这是显示您的选项的快速片段,但这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}`);
}
推荐阅读
- android - 尝试从 Room 数据库获取对象后,订阅 LiveData 导致 null
- angular-material2 - 在 Angular Material 2 版本 6 的下拉列表中动态选择一些选项
- r - 将因子日期 1/1/2017 转换为 2017-01
- python - 将多个列表合并为一个嵌套列表
- swift - Swift 中的类类型工厂
- html - 升级到 5 pro 版后,FontAwesome 图标变大了
- swift - 使用刷新重新加载集合视图
- unit-testing - 使用zookeeper在hadoop minicluster中对hiveserver2进行负载平衡
- mysql - MySQL 中的 set termout off 等价物是什么?
- swift - 无论实现如何,UISegmentedControl 都拒绝工作