【问题标题】:Typescript : check a string for number打字稿:检查数字的字符串
【发布时间】:2015-12-22 02:10:51
【问题描述】:

我是 Web 开发的新手,在我的函数中想要检查给定的字符串值是否是数字。如果字符串不是有效数字,我想返回 null。

以下适用于所有情况,除非字符串为“0”,在这种情况下它返回 null。

parseInt(columnSortSettings[0]) || null;

如何防止这种情况发生。显然 parseInt 不将 0 视为整数!

【问题讨论】:

  • 0 是一个假值..
  • 我已经有一段时间没有发布this link了,但是对于任何学习/使用javascript的人来说,它总是值得一读的

标签: javascript typescript


【解决方案1】:

您可以使用 rxjs 库中的 isNumeric 运算符(导入 rxjs/util/isNumeric

【讨论】:

    【解决方案2】:

    这是因为您基本上是在测试 0 这也是错误的。 你可以这样做

    var n = columnSortSettings[0];
    if(parseInt(n, 10) || n === '0'){
        //...
    }
    

    如果是数字也可以改为测试

    if(typeof(parseInt(n, 10)) === 'number'){
      //...
    }
    

    但要注意原因

    typeof Infinity === 'number';
    typeof NaN === 'number';
    

    【讨论】:

    • 别忘了radix
    • @Andy,是的,完全忘记了 :)
    • 谢谢@Eric。因为 SO 让我只接受一个答案,所以我赞成你的答案。
    【解决方案3】:

    由于 0 是 false ,所以你可以在这种情况下使用 isNaN()

    var res = parseInt(columnSortSettings[0], 10);
    return isNaN(res) ? null : res;
    

    【讨论】:

    • 别忘了radix
    猜你喜欢
    • 2021-08-03
    • 2014-06-19
    • 1970-01-01
    • 2022-07-20
    相关资源
    最近更新 更多