【问题标题】:Typescript: test for Nan, null and undefined only打字稿:仅测试 Nan、null 和 undefined
【发布时间】:2020-07-10 13:36:26
【问题描述】:

我喜欢在 Javascript 中使用!! 来确保设置了变量并且不会引发错误。

但是今天我有一个对我有效的具有0 值的变量。我需要确保它不是 NaN 也不是未定义的,如果没有无聊的 if (variable !== NaN && variable !== undefined,真的没有 short 方法吗?

如果这可能有帮助,我正在使用 angular。

谢谢。

【问题讨论】:

  • undefined 和 NaN 都是假值,所以你可以使用if (variable) { }
  • @JakubJanik,它也会返回 false 为 0,这在这里是不需要的。
  • 仅供参考,variable !== NaN始终为真,因为NaN != NaN。要正确检查NaN,您需要使用isNaN()
  • 根据已经提供的答案,您可以使用if (variable != null && !isNaN(variable))。据我所知,这将是实现您的逻辑的最短方法。

标签: javascript angular typescript


【解决方案1】:

您可以使用 isNan。它将为undefinedNAN 值返回true,但不会为ZERO

const variable = undefined;

 if(isNaN(variable)){
   console.log('I am undefined / NAN'); 
 }else{
   console.log('I am something / zero');
}

【讨论】:

  • 你应该使用isNan()。 ;) 您不能在比较中直接使用NaN。表达式 NaN === NaN 将始终返回 false
  • 在 typescript 中,isNaN() 函数不接受 undefined 参数。错误信息是:Argument of type 'undefined' is not assignable to parameter of type 'number'.
【解决方案2】:
let a = 'value';
if (isNaN(a) || a == null) {
    console.log('a is NaN or null, undefined');
} else {
    // business logic ;)
}

也可以处理 null,caz isNaN(null) // false

【讨论】:

  • 您在此处正确使用a == null 而不是a === null 来检查nullundefined。不错。
  • a == null 不可能在团队中工作,有人可能会认为我忘记了它并添加= 这根本不可读。此外 tslint 可能会拒绝它。
  • @Rolintocour,使用默认的 angular tslint 配置,它运行良好。否则,你应该这样做:`a === null ||一个 === 未定义'。但我更喜欢让它更短。
【解决方案3】:

检查undefined, null, NaN的正确方法是

if(a == null || Number.isNaN(a)) {
  // we did it!
}

请注意使用Number.isNaN 而不仅仅是isNaN。 如果您确实只使用了isNaN,那么您的检查将不会对字符串或空对象等值执行您想要的操作

if(a == null || isNaN(a)) {
  // {} comes in because `isNaN({})` is `true`
  // strings that can't be coerced into numbers 
  // some other funny things
}

阅读更多MDN

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 2022-01-23
    相关资源
    最近更新 更多