最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Typescript : check a string for number - Stack Overflow

programmeradmin2浏览0评论

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.

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

parseInt(columnSortSettings[0]) || null;

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

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.

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

parseInt(columnSortSettings[0]) || null;

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

Share Improve this question edited Feb 19, 2018 at 16:16 Rahul Misra asked Sep 24, 2015 at 12:56 Rahul MisraRahul Misra 6692 gold badges8 silver badges16 bronze badges 2
  • 2 0 is a falsy value .. – Hacketo Commented Sep 24, 2015 at 12:59
  • 2 I haven't posted this link in a while, but it's always worth a read for anyone learning/using javascript – musefan Commented Sep 24, 2015 at 13:35
Add a comment  | 

3 Answers 3

Reset to default 9

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

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

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

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';

You can use the isNumeric operator from rxjs library (importing rxjs/util/isNumeric

发布评论

评论列表(0)

  1. 暂无评论