【问题标题】:How to write a Generalized function to perform OR operation in TypeScript?如何编写通用函数以在 TypeScript 中执行 OR 操作?
【发布时间】:2021-12-28 02:35:30
【问题描述】:

在 TypeScript 中,有没有一种方法可以创建一个通用函数来对传递的任意数量的参数执行 OR 运算?

我可以为 2 个参数编写一个函数。要求是对任意数量的参数进行概括。

export const performOR = (arg1, arg2) => arg1 || arg2;

const isArg1OrArg2 = performOR(x, y);

如果这可以通过传递参数数组来实现,那也很好。

【问题讨论】:

  • 你总是可以传递一个参数数组并循环它们。

标签: typescript operators


【解决方案1】:

这听起来像是家庭作业,但是:

export const performOR = (...args: any[]):boolean  => {
  for(const item of args) {
    if (item) return true;
  }
  return false;
}

【讨论】:

    【解决方案2】:

    在上面发布的答案的帮助下,我通过一些修改概括了 OR 和 AND 操作。可能对寻求类似解决方案的任何其他人有所帮助。

    const performOR = (...args: any[]):boolean  => {  
      return args.some(arg => arg === true);
    }
    
    const performAND = (...args: any[]):boolean  => {  
      return args.every(arg => arg === true);
    }
    
    performOR(true, false);
    performAND(true, true);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多