开发者

How do I check if a JavaScript parameter is a number?

I'm doing some trouble-shooting and want to add a check th开发者_运维问答at a parameter to a function is a number. How do I do this?

Something like this...

function fn(id) {
    return // true iff id is a number else false
}

Even better is if I can check that the parameter is a number AND a valid integer.


function fn(id) {
    return typeof(id) === 'number';
}

To also check if it’s an integer:

function fn(id) {
    return typeof(id) === 'number' &&
            isFinite(id) &&
            Math.round(id) === id;
}


i'd say

 n === parseInt(n)

is enough. note three '===' - it checks both type and value


Check if the type is number, and whether it is an int using parseInt:

if (typeof id == "number" && id == parseInt(id))


=== means strictly equals to and == checks if values are equal. that means "2"==2 is true but "2"===2 is false.

using regular expression

var intRegex = /^\d+$/;
if(intRegex.test(num1)) { 
//num1 is a valid integer
}

example of == vs. ===


function fn(id){ 
  if((parseFloat(id) == parseInt(id)) && !isNaN(id)){
      return true;
  } else { 
      return false;
  } 
}


function fn(id) {
    var x = /^(\+|-)?\d+$/;
    if (x.test(id)) {
        //integer
        return true;
    }
    else {
        //not an integer
        return false;
    }
}

Test fiddle: http://jsfiddle.net/xLYW7/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜