JavaScript中的(内置)方式,用于检查字符串是否为有效数字 [英] (Built-in) way in JavaScript to check if a string is a valid number

查看:191
本文介绍了JavaScript中的(内置)方式,用于检查字符串是否为有效数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在旧的VB6 IsNumeric()函数的概念空间中有什么东西?

I'm hoping there's something in the same conceptual space as the old VB6 IsNumeric() function?

推荐答案

要检查变量(包括字符串)是否为数字,请检查它是否为数字:



此工作原理无论变量包含的是字符串还是数字。

To check if a variable (including a string) is a number, check if it is not a number:

This works regardless of whether the variable contains is a string or number.

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



示例



Examples

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

当然,如果需要,你可以否定这一点。例如,要实现您给出的 IsNumeric 示例:

Of course, you can negate this if you need to. For example, to implement the IsNumeric example you gave:

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



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



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

To convert a string containing a number into a number:

only works if the string only contains numeric characters, else it returns NaN.

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



示例



Examples

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



将字符串松散地转换为数字



对转换有用'12px'到12,例如:

To convert a string loosely to a number

useful for converting '12px' to 12, for example:

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



示例



Examples

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() 因为这种行为,你可能最好还是使用另一种方法):

Floats

Bear in mind that, unlike +num, parseInt (as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use parseInt() because of this behaviour, you're probably better off using another method instead):

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



空字符串



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

Empty strings

Empty strings may be a little counter-intuitive. +num converts empty strings to zero, and isNaN() assumes the same:

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

parseInt()不同意:

parseInt('')       // NaN

这篇关于JavaScript中的(内置)方式,用于检查字符串是否为有效数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆