简体   繁体   English

测试子字符串是否为数字,并且是否大于Javascript中的另一个数字

[英]Test if substring is a number and if it is larger than another number in Javascript

I have a json file that has a string as the pubDate. 我有一个以pubDate为字符串的json文件。 The pubDate could be 2010 or 2010 Mar or 2010/1/1 or Blank or Not available. pubDate可以是2010或2010 Mar或2010/1/1或Blank或Not available。 What I have is 我有的是

var res = pubDate.substr(0, 4);
var i = parseInt(res, 10);
if (!isNaN(i)) {                    
    if (i > 2010) {
        //do work
    }
}

This works but I'd love to have some cleaner code where I might be able to do it in one or two lines of code. 这行得通,但是我很想拥有一些更简洁的代码,使我可以在一两行代码中做到这一点。 This this possible? 这可能吗?

1) If i is NaN , i > 2010 will be false, so the isNaN check is not neccessary. 1)如果iNaN ,则i > 2010将为false,因此不需要进行isNaN检查。

2) ParseInt ignores suffix characters, so you don't have to substr: 2)ParseInt忽略后缀字符,因此您不必强制执行以下操作:

const year = parseInt(pubDate);
if(year > 2010) {
  //...
 }

That's a pretty messy situation it sounds like, short of collapsing some of those lines I don't think you have much of an option. 听起来这是一个非常混乱的情况,没有折叠其中的一些行,我认为您没有太多选择。 By collapsing some of the lines I mean literally: 通过折叠一些行,我的意思是:

var i = parseInt((pubDate.substr(0, 4), 10);
if (!isNan(i) && i > 2010) {
    // do work
}

But this is assuming you don't need "res" for something later, which looks like you shouldn't. 但这是假设您以后不需要使用“ res”,看起来您不需要。

Maybe two lines of code. 也许两行代码。 Maybe not cleaner code. 也许不是更干净的代码。

var i = (!isNaN(parseInt(pubDate.substr(0, 4))))?parseInt(pubDate.substr(0, 4)):0;
if( i > 2010 ){
    //do work
}

If you are not looking for decimal specific you could remove the 10. More information about this on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt 如果您不查找特定于小数的数字,则可以删除10。有关此的更多信息, 请访问https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

var i = parseInt(pubDate.substr(0, 4));
if (!isNaN(i) && i > 2010) { 
     //do work
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM