首页 > 解决方案 > 有没有办法为带有验证键是否存在的情况的对象设置 switch 语句?- javascript

问题描述

我的目标:将 if 语句链转换为 switch 语句,并让它通过案例
我正在处理的内容:解码的 Minecraft NBT 数据(基本上只是一个对象)
我的问题是:我不确定是否有 switch语句将用于检测对象中是否存在键,除非我执行大量 switch 语句,但如果我使用 if 语句链会更容易。
一个对象的示例如下所示:

nbt = {
  type: 'compound',
  name: '',
  value: {
    i: {
      type: 'list',
      value: {
        type: 'compound',
        value: [
          {
            id: { type: 'short', value: 276 },
            Count: { type: 'byte', value: 1 },
            tag: {
              type: 'compound',
              value: {
                Unbreakable: { type: 'byte', value: 1 },
                HideFlags: { type: 'int', value: 254 },
                display: {
                  type: 'compound',
                  value: {
                    Lore: {
                      type: 'list',
                      value: {
                        type: 'string',
                        value: [
                          '§7Damage: §c+35',
                          '',
                          '§7§8This item can be reforged!',
                          '§a§lUNCOMMON SWORD'
                        ]
                      }
                    },
                    Name: { type: 'string', value: '§aDiamond Sword' }
                  }
                },
                ExtraAttributes: {
                  type: 'compound',
                  value: {
                    originTag: { type: 'string', value: 'CRAFTING_GRID_SHIFT' },
                    id: { type: 'string', value: 'DIAMOND_SWORD' },
                    uuid: {
                      type: 'string',
                      value: '3aa2d326-541f-4a2e-abae-04366b4771d3'
                    },
                    timestamp: { type: 'string', value: '6/1/21 8:44 PM' }
                  }
                }
              }
            },
            Damage: { type: 'short', value: 0 }
          }
        ]
      }
    }
  }
}

在此之后,我删除了一些不必要的键,我得到了这样的东西:

{
  name: '§aDiamond Sword',
  lore: [
    '§7Damage: §c+35',
    '',
    '§7§8This item can be reforged!',
    '§a§lUNCOMMON SWORD'
  ],
  attributes: {
    rarity_upgrades: undefined,
    modifier: undefined,
    dungeon_item_level: undefined,
    dungeon_master_level: 0,
    hot_potato_count: undefined,
    fuming_potato_count: 0,
    art_of_war_count: undefined,
    enchantments: undefined,
    runes: undefined,
    ability_scroll: undefined,
    id: 'DIAMOND_SWORD'
  }
}

(每件物品都有不同的修饰符,有的有符文,有的没有,有的有能力卷轴之类的特殊物品,但是这个物品是完全干净的,上面什么都没有,这就是为什么你undefined在很多领域看到的原因。如果一个项目没有,比如说,能力卷轴,它只是不会在 NBT 对象中。)
我设想的案例陈述看起来像这样:

switch (item_schema) {
  case item_schema.attributes.fuming_potato_count > 10:
    console.log('Detected Fuming HPBs')
  case item_schema.attributes.dungeon_item_level > 5:
    console.log('Detected Master Stars')
  case typeof item_schema.attributes.ability_scroll !== 'undefined':
    console.log('Detected Necron\'s Blade Ability Scrolls')
  case typeof item_schema.attributes.enchantments !== 'undefined':
    console.log('Detected Enchantments')
  default:
    console.log('No Modifiers Detected')
}

这甚至可能吗?我只是想清理我的代码,在此之前我只有一个 if 语句链,但我觉得这可能是一种更简单、更清洁的方法。提前致谢 :)

标签: javascriptobjectminecraft

解决方案


一种选择是使用速记标识符将您的测试合并到一个对象中

const cond = [
{'Detected Fuming HPBs': item_schema.attributes.fuming_potato_count > 10,
'Detected Master Stars': item_schema.attributes.dungeon_item_level > 5
}

.. 等等。然后你可以在你需要的地方测试它们或循环它们以输出

let x = 3,
  y = 4
const cond = [
{'X is 4': x === 4},
{'X is less than 20': x < 20},
{'Y is 4': y === 4}
];

cond.forEach(obj => {
  const [output, condition] = Object.entries(obj)[0];
  console.log(output, "? :: ", condition)
});


使用switch

您总是想运行开关,因此将其设置为始终处理,true但结果可能不是您所期望的:

与每个 case 标签关联的可选 break 语句确保程序在执行匹配的语句后跳出 switch,并在 switch 后面的语句处继续执行。如果省略了break,程序将继续执行switch语句中的下一条语句。如果在它之前有 return 语句,则不需要 break 语句。

let hasCondition = false
switch (true) {
  case item_schema.attributes.fuming_potato_count > 10:
    console.log('Detected Fuming HPBs');
    hasCondition = true;
  case item_schema.attributes.dungeon_item_level > 5:
    console.log('Detected Master Stars')
    hasCondition = true;
  //case typeof item_schema.attributes.ability_scroll !== 'undefined':
  case item_schema.attributes.hasOwnProperty("ability_scroll"):
    console.log('Detected Necron\'s Blade Ability Scrolls')
    hasCondition = true;
  //case item_schema.attributes.enchantments !== 'undefined':
  case item_schema.attributes.hasOwnProperty("enchantments"):
    console.log('Detected Enchantments')
    hasCondition = true;
}

如果您不想break;在 each 之后放置语句case:,则需要在default其他地方处理条件,因为它总是会运行。

if (!hasCondition) console.log('No Modifiers Detected')

取自:https ://dev.to/jasterix/using-a-switch-statement-with-logical-operators-17ni


推荐阅读