要检查变量(包括字符串)是否为数字,请检查其是否不是数字:
无论变量内容是字符串还是数字,这都有效。
isNaN(num) // returns true if the variable does NOT contain a valid number
例子
isNaN(123) // falseisNaN('123') // falseisNaN('1e10000') // false (This translates to Infinity, which is a number)isNaN('foo') // trueisNaN('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') // 12parseInt('aaa') // NaNparseInt('12px') // 12parseInt('foo2') // NaN These last two may be differentparseInt('12a5') // 12 from what you expected to see.浮点数
请记住,与
+num,
parseInt(顾名思义)不同,会通过截取小数点后的所有内容来将浮点数转换为整数(如果
parseInt()由于
这种行为 而 要使用 的 话,最好改用其他方法) :
+'12.345' // 12.345parseInt(12.345) // 12parseInt('12.345') // 12空字符串
空字符串可能有点违反直觉。
+num将空字符串或带空格的字符串转换为零,并
isNaN()假定相同:
+'' // 0+' ' // 0isNaN('') // falseisNaN(' ') // false但
parseInt()不同意:
parseInt('') // NaNparseInt(' ') // NaN


