0

可能重复:
JavaScript 中是否有(内置)方法来检查字符串是否为有效数字?

我在 riak map reduce 工作中使用 JS。我有一个要映射的数字,并且需要是一个数字。

如果我有一个变量:

 var wp=sfggz5341&& or var=100

if如何测试数字?

例如

if wp==Number:    
    OK 
else:    
    pass
4

5 回答 5

2

您可以使用以下方法进行测试:if (!isNaN(+wp)). 换句话说,将“可能是数字”转换为数字(使用+运算符。如果不能转换,则结果为NaN. 所以!isNaN(...)表示它是一个数字。

于 2013-01-24T06:48:32.963 回答
2

你可以使用typeof操作符(详见MDN):

var wp = "sfggz53141";
if (typeof wp === "number") {
    // number here
} else if (typeof wp === "string") {
    // string here
}
于 2013-01-24T06:48:42.433 回答
0

您可以使用isNaN()isNumeric()

isNumeric()可以使用,但在以下情况下会失败:

// Whitespace strings:
IsNumeric(' ') == true;
IsNumeric('\t\t') == true;
IsNumeric('\n\r') == true;

// Number literals:
IsNumeric(-1) == false;
IsNumeric(0) == false;
IsNumeric(1.1) == false;
IsNumeric(8e5) == false;

所以最好的方法是:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

参考: https ://stackoverflow.com/a/1830844/462627

于 2013-01-24T06:48:59.357 回答
0

您可以使用!NaN(wp)来检查字符串是否为数字。

于 2013-01-24T06:49:30.153 回答
0

尝试使用
isNaN()

如果值为 NaN,则此函数返回 true,否则返回 false。

于 2013-01-24T06:49:49.923 回答