我希望有与旧的VB6 IsNumeric()
函数在同一概念空间中的东西?
我希望有与旧的VB6 IsNumeric()
函数在同一概念空间中的东西?
.
”以外的数字分隔符。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
来“检查一个变量是否不是数字”。“不是数字”并不等于“IEEE-794 NaN”,而这正是 isNaN
进行测试的内容。特别是在测试布尔值和空字符串时,这种用法会失败。请参见 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/isNaN#Description 。 - EMLvar n = 'a'; if (+n === +n) { // is number }
在最新版本的Chrome中,它比isNaN快约3994%。在这里查看性能测试:http://jsperf.com/isnan-vs-typeof/5 - Kevin JurkowskiisNaN(1 + false + parseInt("1.do you trust your users?"))
请问你信任你的用户吗? - keithpjolley如果您只是想检查字符串是否为整数(没有小数),则正则表达式是一个不错的选择。其他方法,例如isNaN
对于如此简单的事情来说太复杂了。
function isNumeric(value) {
return /^-?\d+$/.test(value);
}
console.log(isNumeric('abcd')); // false
console.log(isNumeric('123a')); // false
console.log(isNumeric('1')); // true
console.log(isNumeric('1234567890')); // true
console.log(isNumeric('-23')); // true
console.log(isNumeric(1234)); // true
console.log(isNumeric(1234n)); // true
console.log(isNumeric('123.4')); // false
console.log(isNumeric('')); // false
console.log(isNumeric(undefined)); // false
console.log(isNumeric(null)); // false
只允许使用正数整数,请使用以下内容:
function isNumeric(value) {
return /^\d+$/.test(value);
}
console.log(isNumeric('123')); // true
console.log(isNumeric('-23')); // false
/^[0-9]+$/.test(value)
- Devin Rhode这个问题的被接受答案有一些缺陷(正如其他几位用户所强调的那样)。以下是在JavaScript中处理这个问题的最简单和经过验证的方法之一:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
以下是一些好的测试用例:
console.log(isNumeric(12345678912345678912)); // true
console.log(isNumeric('2 ')); // true
console.log(isNumeric('-32.2 ')); // true
console.log(isNumeric(-32.2)); // true
console.log(isNumeric(undefined)); // false
// the accepted answer fails at these tests:
console.log(isNumeric('')); // false
console.log(isNumeric(null)); // false
console.log(isNumeric([])); // false
parseFloat
不适用于此应用程序,因为当它遇到第一个无法解析为数字的字符时,它将返回已解析的有效数字。例如,parseFloat('1.1ea10') === 1.1
。因此需要其他方法来确保字符串被完全解析为数字。 - Ben AstonNumber.isNaN
和 Number.isFinite
不起作用,因为它们不会将字符串转换为数字。 - Cas!isNaN(parseFloat('0111')) && isFinite('0111') === true
- MrYellow你可以使用正则表达式的方式:
var num = "987238";
if(num.match(/^-?\d+$/)){
//valid integer (positive or negative)
}else if(num.match(/^\d+\.\d+$/)){
//valid float
}else{
//not valid number
}
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
parseFloat()
返回数字的每种情况下,Number()
(和isNaN()
)都会做正确的事情,并反之亦然。因此,为了确定一个字符串是否确切且只是一个数字,请调用两个函数,并查看它们是否同时返回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))
}
' 1'
,'2 '
和' 3'
都会返回true。 - Rudey也许这个问题已经被反复讨论过很多次了,但是今天我也遇到了这个问题,并且想要发布我的答案,因为我没有看到其他任何一个答案能够像我这样简单而彻底地解决它:
var isNumeric = function(num){
return (typeof(num) === 'number' || typeof(num) === "string" && num.trim() !== '') && !isNaN(num);
}
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”。
或者,查看每个用例的返回值:
isNumeric('3e2')
/ isNumeric(3e2)
- Kieran101(typeof('0111') === 'number' || typeof('0111') === "string" && '0111'.trim() !== '') && !isNaN('0111');
因此数据丢失,即意图的零前缀。 - MrYellow尝试使用isNaN函数:
isNaN()函数用于确定一个值是否为不合法的数字(非数值)。
如果值等于NaN,则该函数返回true。否则,返回false。
此函数与Number特定的Number.isNaN()方法不同。
全局的isNaN()函数会将被测试的值转换为数字,然后进行测试。
Number.isNan()不会将值转换为数字,并且对任何不属于Number类型的值都不会返回true...
isNaN()
对于任何仅包含空格字符的字符串,包括像'\u00A0'这样的字符,都会返回false。 - Michael这取决于你想将什么解析为数字。
由于现有的资料都不能满足我的需求,我试图搞清楚这些函数实际上是如何工作的。
对于这个问题的三个直接回答感觉如下:
!isNaN(input)
(它与 +input === +input
的输出相同)!isNaN(parseFloat(input))
isFinite(input)
但它们在每种情况下都正确吗?
我在几种情况下测试了这些功能,并生成了 markdown 输出,看起来像这样:
input |
!isNaN(input) 或者 +input===+input |
!isNaN( parseFloat( input)) |
isFinite( input) |
评论 |
---|---|---|---|---|
123 | ✔️ | ✔️ | ✔️ | - |
'123' | ✔️ | ✔️ | ✔️ | - |
12.3 | ✔️ | ✔️ | ✔️ | - |
'12.3' | ✔️ | ✔️ | ✔️ | - |
' 12.3 ' | ✔️ | ✔️ | ✔️ | 剪裁空白字符,如预期所示。 |
1_000_000 | ✔️ | ✔️ | ✔️ | 理解数字分隔符,也是预期的。 |
'1_000_000' | ❌ | ✔️ | ❌ | 惊喜!JS在字符串中不会解析数字分隔符。有关详情,请查看this问题。(那么为什么将其解析为浮点数呢?好吧,它没有。) |
'0b11111111' | ✔️ | ✔️ | ✔️ | 理解二进制形式,应该是这样的。 |
'0o377' | ✔️ | ✔️ | ✔️ | 八进制形式也被理解了。 |
'0xFF' | ✔️ | ✔️ | ✔️ | 当然,十六进制是可以理解的。有人认为会有什么问题吗? |
''那么,哪一个是“正确”的呢?
现在应该清楚了,这主要取决于我们的需求。例如,我们可能希望将空输入视为0。在这种情况下, 同样地,当需要将1010000000000 视为有效数字时,也许我们可以从 当然,我们可以手动排除任何一种情况。 就像在我的情况下,我需要完全符合
而且,这是我生成表格的 JavaScript 代码:
|
isFinite()
用于检查一个值是否是有效(有限)数字。let a = isFinite('abc') // false
let b = isFinite('123') // true
let c = isFinite('12a') // false
let d = isFinite(null) // true
console.log(a, b, c, d)
虽然这是一个旧问题,但给出的答案中还有一些要点缺失。
科学计数法。
!isNaN('1e+30')
的值为 true
,但在大多数情况下,当人们要求数字时,他们不希望匹配类似于 1e+30
的内容。
大浮点数可能会表现出奇怪的行为
观察以下示例(使用Node.js):
> var s = Array(16 + 1).join('9')
undefined
> s.length
16
> s
'9999999999999999'
> !isNaN(s)
true
> Number(s)
10000000000000000
> String(Number(s)) === s
false
>
另一方面:
> var s = Array(16 + 1).join('1')
undefined
> String(Number(s)) === s
true
> var s = Array(15 + 1).join('9')
undefined
> String(Number(s)) === s
true
>
因此,如果有人期望 String(Number(s)) === s
,那么最好将字符串限制在最多15个数字(忽略前导零)。
无穷大
> typeof Infinity
'number'
> !isNaN('Infinity')
true
> isFinite('Infinity')
false
>
鉴于这一切,检查给定的字符串是否是满足以下所有条件的数字并不是一件容易的事情:
Number
,然后再转回 String
下面是一个简单版本:
function isNonScientificNumberString(o) {
if (!o || typeof o !== 'string') {
// Should not be given anything but strings.
return false;
}
return o.length <= 15 && o.indexOf('e+') < 0 && o.indexOf('E+') < 0 && !isNaN(o) && isFinite(o);
}
然而,即使这个方法也远未完美。该方法未处理前导零,但前导零会影响长度测试。
isNaN("")
、isNaN(" ")
、isNaN(false)
等情况下失败了。它返回false
,这意味着它们是数字。 - Andrew