您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

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
javascript 2022/1/1 18:17:34 有464人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶