【问题标题】:Javascript refactoring spaghetti code of if/elseJavascript 重构 if/else 的意大利面条代码
【发布时间】:2021-02-03 18:20:13
【问题描述】:

想象一个函数,它返回一个包含 3 个字段的对象。

现在,我为数组中的每个元素调用函数并解构这些字段

 const array = [1, 2, 3];
 
 for (const element of array) {
    const {
      field1,
      field2,
      field3,
    } = await function(element);
    ...
 }

我需要检查这 3 个字段的值是否不包含在这个标记数组中:

 const DANGEROUS_TOKENS = ["possible", "sure"];

如果包含其中一个,我必须打破循环(忽略下一次迭代)

这就是我正在做的:

for (const element of array) {
   const {
     field1,
     field2,
     field3,
     ...,
     fieldN
   } = await function(element);
        
   if (DANGEROUS_TOKENS.includes(field1)) {
      handleElement();
      break;
   } else if(DANGEROUS_TOKENS.includes(field2)) {
      handleElement();
      break;
   } ... the same for the next fields
}

如何避免这个冗长的 if-else 指令?

【问题讨论】:

    标签: javascript ecmascript-6 refactoring


    【解决方案1】:

    听起来你只需要一个属性数组来迭代:

    const props = ['field1', 'field2', 'field3'];
    for (const element of array) {
      const result = await theFunction(element);
      if (props.some(prop => DANGEROUS_TOKENS.includes(result[prop]))) {
        handleElement();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多