小编典典

JavaScript中的(内置)方式来检查字符串是否为有效数字

spring

我希望与旧的VB6 IsNumeric()函数在同一概念空间中存在某些东西吗?


阅读 398

收藏
2020-04-26

共1个答案

小编典典

要检查变量(包括字符串)是否为数字,请检查其是否不是数字:
无论变量内容是字符串还是数字,这都有效。

isNaN(num)         // returns true if the variable does NOT contain a valid number

例子

isNaN(123)         // false
isNaN('123')       // false
isNaN('1e10000')   // false (This translates to Infinity, which is a number)
isNaN('foo')       // true
isNaN('10px')      // true

当然,你可以根据需要对此进行否定。例如,要实现IsNumeric你给出的示例:

function isNumeric(num){
  return !isNaN(num)
}

要将包含数字的字符串转换为数字:

仅当字符串仅包含数字字符时才有效,否则返回NaN。

+num               // returns the numeric value of the string, or NaN 
                   // if the string isn't purely numeric characters

例子

+'12'              // 12
+'12.'             // 12
+'12..'            // NaN
+'.12'             // 0.12
+'..12'            // NaN
+'foo'             // NaN
+'12px'            // NaN

将字符串宽松地转换为数字有助于将“ 12px”转换为12,例如:

parseInt(num)      // extracts a numeric value from the 
                   // start of the string, or NaN.

例子

parseInt('12')     // 12
parseInt('aaa')    // NaN
parseInt('12px')   // 12
parseInt('foo2')   // NaN      These last two may be different
parseInt('12a5')   // 12       from what you expected to see. 

浮点数

请记住,与+num,parseInt(顾名思义)不同,会通过截取小数点后的所有内容来将浮点数转换为整数(如果parseInt() 由于这种行为而要使用的话,最好改用其他方法) :

+'12.345'          // 12.345
parseInt(12.345)   // 12
parseInt('12.345') // 12

空字符串

空字符串可能有点违反直觉。+num将空字符串或带空格的字符串转换为零,并isNaN()假定相同:

+''                // 0
+'   '             // 0
isNaN('')          // false
isNaN('   ')       // false

但parseInt()不同意:

parseInt('')       // NaN
parseInt('   ')    // NaN
2020-04-26