typescript 打字稿:检查字符串中的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32761930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:06:07  来源:igfitidea点击:

Typescript : check a string for number

javascripttypescript

提问by Rahul Misra

I'm new to web development, and in my function want to check if a given string value is a number. In case the string isn't a valid number I want to return null.

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

The following works for all cases except when the string is "0" in which case it returns null.

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

parseInt(columnSortSettings[0]) || null;

How do I prevent this from happening. Apparantly parseInt doesn't consider 0 as an integer!

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

回答by Pranav C Balan

Since 0is act as false , so you can use isNaN()in this case

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

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

回答by Eric

It's because you are basically testing 0 which is also false. You can do

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

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

You can also test instead if it's a number

你也可以测试它是否是一个数字

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

But beware cause

但要注意原因

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

回答by Richard Lee

You can use the isNumericoperator from rxjslibrary (importing rxjs/util/isNumeric

您可以使用ISNUMERIC从运营商rxjs库(进口rxjs / UTIL / ISNUMERIC