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


当前回答

2020年10月2日:请注意,许多简单的方法都充满了微妙的错误(例如空白、隐式部分解析、基数、数组强制等),这里的许多答案都没有考虑到。以下实现可能适用于您,但请注意,它不适用于小数点“.”以外的数字分隔符:

function isNumeric(str) {
  if (typeof str != "string") return false // we only process strings!  
  return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
         !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}

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

无论变量内容是字符串还是数字,这都是有效的。

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
isNaN('')          // false
isNaN(' ')         // false
isNaN(false)       // false

当然,如果需要,您可以否定这一点。例如,要实现您给出的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 three may
parseInt('12a5')   // 12       be different from what
parseInt('0x10')   // 16       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

其他回答

报价:

isNaN(num)//如果变量不包含有效数字,则返回true

如果您需要检查前导/尾随空格,则不完全正确-例如,当需要一定数量的数字时,并且您需要获得例如“1111”而不是“111”或“111”以获得PIN输入。

更好使用:

var num = /^\d+$/.test(num)

尝试isNan函数:

isNaN()函数确定值是否为非法数字(Not-a-number)。如果值等于NaN,则此函数返回true。否则返回false。此函数与特定于Number的Number.isNaN()方法不同。全局isNaN()函数将测试值转换为Number,然后对其进行测试。Number.isNan()不会将值转换为Number,并且对于任何非Number类型的值都不会返回true。。。

有些人也可能从基于正则表达式的答案中受益。这里是:

一行是Integer:

const isInteger = num => /^-?[0-9]+$/.test(num+'');

一行是Numeric:接受整数和小数

const isNumeric = num => /^-?[0-9]+(?:\.[0-9]+)?$/.test(num+'');

如果您真的想确保字符串只包含一个数字、任何数字(整数或浮点)以及一个数字,则不能使用parseInt()/parseFloat()、number()或!isNaN()。注意!isNaN()实际上在Number()返回一个数字时返回true,在返回NaN时返回false,因此我将从后面的讨论中排除它。

parseFloat()的问题是,如果字符串包含任何数字,它将返回一个数字,即使字符串不只包含一个数字:

parseFloat("2016-12-31")  // returns 2016
parseFloat("1-1") // return 1
parseFloat("1.2.3") // returns 1.2

Number()的问题是,在传递的值根本不是数字的情况下,它将返回一个数字!

Number("") // returns 0
Number(" ") // returns 0
Number(" \u00A0   \t\n\r") // returns 0

滚动自己的正则表达式的问题是,除非您创建了与Javascript识别的浮点数匹配的精确正则表达式,否则您将错过案例或识别不应该出现的案例。即使您可以滚动自己的正则表达式,为什么?有更简单的内置方法来实现。

然而,事实证明,Number()(和isNaN())在parseFloat()不应该返回数字的情况下都做了正确的事情,反之亦然。因此,要确定字符串是否真的是一个数字,请调用这两个函数,看看它们是否都返回true:

function isNumber(str) {
  if (typeof str != "string") return false // we only process strings!
  // could also coerce to string: str = ""+str
  return !isNaN(str) && !isNaN(parseFloat(str))
}

2019:包括ES3、ES6和TypeScript示例

也许这已经被重复了太多次了,但是我今天也和这一个进行了斗争,并想发布我的答案,因为我没有看到任何其他答案能如此简单或彻底地做到这一点:

ES3

var isNumeric = function(num){
    return (typeof(num) === 'number' || typeof(num) === "string" && num.trim() !== '') && !isNaN(num);  
}

ES6

const isNumeric = (num) => (typeof(num) === 'number' || typeof(num) === "string" && num.trim() !== '') && !isNaN(num);

字体

const isNumeric = (num: any) => (typeof(num) === 'number' || typeof(num) === "string" && num.trim() !== '') && !isNaN(num as number);

这似乎很简单,涵盖了我在许多其他帖子中看到的所有基础,并自己思考:

// Positive Cases
console.log(0, isNumeric(0) === true);
console.log(1, isNumeric(1) === true);
console.log(1234567890, isNumeric(1234567890) === true);
console.log('1234567890', isNumeric('1234567890') === true);
console.log('0', isNumeric('0') === true);
console.log('1', isNumeric('1') === true);
console.log('1.1', isNumeric('1.1') === true);
console.log('-1', isNumeric('-1') === true);
console.log('-1.2354', isNumeric('-1.2354') === true);
console.log('-1234567890', isNumeric('-1234567890') === true);
console.log(-1, isNumeric(-1) === true);
console.log(-32.1, isNumeric(-32.1) === true);
console.log('0x1', isNumeric('0x1') === true);  // Valid number in hex
// Negative Cases
console.log(true, isNumeric(true) === false);
console.log(false, isNumeric(false) === false);
console.log('1..1', isNumeric('1..1') === false);
console.log('1,1', isNumeric('1,1') === false);
console.log('-32.1.12', isNumeric('-32.1.12') === false);
console.log('[blank]', isNumeric('') === false);
console.log('[spaces]', isNumeric('   ') === false);
console.log('null', isNumeric(null) === false);
console.log('undefined', isNumeric(undefined) === false);
console.log([], isNumeric([]) === false);
console.log('NaN', isNumeric(NaN) === false);

您还可以尝试自己的isNumeric函数,并在这些用例中刚刚过去,然后扫描所有用例的“true”。

或者,查看每个返回的值: