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 content 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
Of course, you can negate this if you need to.
(当然,您可以根据需要对此进行否定。)
For example, to implement the IsNumeric
example you gave:(例如,要实现您提供的IsNumeric
示例:)
function isNumeric(num){
return !isNaN(num)
}
To convert a string containing a number into a number:(要将包含数字的字符串转换为数字:)
Only works if the string only contains numeric characters, else it returns NaN
.
(仅当字符串仅包含数字字符时才有效,否则返回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
To convert a string loosely to a number(将字符串宽松地转换为数字)
Useful for converting '12px' to 12, for example:
(有助于将“ 12px”转换为12,例如:)
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.
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 ):
(请记住,与+num
不同, parseInt
(顾名思义)将通过截取小数点后的所有内容将浮点数转换为整数(如果由于这种行为而想使用parseInt()
,则可能更好)使用另一种方法代替 ):)
+'12.345' // 12.345
parseInt(12.345) // 12
parseInt('12.345') // 12
Empty strings(空字符串)
Empty strings may be a little counter-intuitive.
(空字符串可能有点违反直觉。)
+num
converts empty strings to zero, and isNaN()
assumes the same:(+num
将空字符串转换为零,并且isNaN()
假定相同:)
+'' // 0
isNaN('') // false
But parseInt()
does not agree:
(但是parseInt()
不同意:)
parseInt('') // NaN