本文共 17015 字,大约阅读时间需要 56 分钟。
我希望在与旧的VB6 Is()
函数相同的概念空间中有东西吗?
引用:
isNaN(num)//如果变量不包含有效数字,则返回true
如果您需要检查前导/后缀空格,例如,当需要一定数量的数字,并且需要输入例如“ 1111”而不是“ 111”或“ 111”时,则并非完全正确输入。
更好地使用:
var num = /^\d+$/.test(num)
尝试 :
isNaN()函数确定一个值是否为非法数字(非数字)。
如果该值等于NaN,则此函数返回true。 否则,它返回false。
此函数不同于Number特定方法。
全局isNaN()函数,将测试的值转换为Number,然后对其进行测试。
Number.isNan()不会将值转换为Number,并且对于任何非Number类型的值也不会返回true。
parseInt(),但请注意此函数在某种意义上有所不同,例如,它为parseInt(“ 100px”)返回100。
您可以使用RegExp方式:
var num = "987238";if(num.match(/^-{0,1}\d+$/)){ //valid integer (positive or negative)}else if(num.match(/^\d+\.\d+$/)){ //valid float}else{ //not valid number}
无论变量内容是字符串还是数字,这都有效。
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()
假定相同:
+'' // 0isNaN('') // false
但是parseInt()
不同意:
parseInt('') // NaN
旧问题,但给出的答案中缺少几点。
科学计数法。
!isNaN('1e+30')
是true
,但是在大多数情况下,当人们要求输入数字时,他们不想匹配1e+30
类的东西。
较大的浮点数可能会表现出怪异
观察(使用Node.js):
> var s = Array(16 + 1).join('9')undefined> s.length16> s'9999999999999999'> !isNaN(s)true> Number(s)10000000000000000> String(Number(s)) === sfalse>
另一方面:
> var s = Array(16 + 1).join('1')undefined> String(Number(s)) === strue> var s = Array(15 + 1).join('9')undefined> String(Number(s)) === strue>
因此,如果期望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); }
但是,即使这一步也远远不够。 此处不处理前导零,但它们会拧长长度测试。
PFB的工作解决方案:
function(check){ check = check + ""; var isNumber = check.trim().length>0? !isNaN(check):false; return isNumber; }
如果您只是想检查字符串是否为整数(无小数点),则正则表达式是一种不错的选择。 诸如isNaN
类的其他方法对于如此简单的事物而言过于复杂。
function isNumeric(value) { return /^-{0,1}\d+$/.test(value);}console.log(isNumeric('abcd')); // falseconsole.log(isNumeric('123a')); // falseconsole.log(isNumeric('1')); // trueconsole.log(isNumeric('1234567890')); // trueconsole.log(isNumeric('-23')); // trueconsole.log(isNumeric(1234)); // trueconsole.log(isNumeric('123.4')); // falseconsole.log(isNumeric('')); // falseconsole.log(isNumeric(undefined)); // falseconsole.log(isNumeric(null)); // false
要只允许正整数使用此:
function isNumeric(value) { return /^\d+$/.test(value);}console.log(isNumeric('123')); // trueconsole.log(isNumeric('-23')); // false
在我的应用程序中,我们仅允许使用AZ AZ和0-9字符。 我发现使用“ 字符串 %1 === 0”的上述答案有效,除非字符串以0xnn开头(例如0x10),然后在我们不希望使用字符串时将其返回为数字。 在我们的数字检查中,以下简单的陷阱似乎可以解决我们的特定情况。
function isStringNumeric(str_input){ //concat a temporary 1 during the modulus to keep a beginning hex switch combination from messing us up //very simple and as long as special characters (non a-z A-Z 0-9) are trapped it is fine return '1'.concat(str_input) % 1 === 0;}
警告 :这可能是利用Javascript和Actionscript [Number(“ 1” + the_string)%1 === 0)]中的一个长期错误,我不能代表这个,但这正是我们所需要的。
我的解决方案:
// returns true for positive ints; // no scientific notation, hexadecimals or floating point dotsvar isPositiveInt = function(str) { var result = true, chr; for (var i = 0, n = str.length; i < n; i++) { chr = str.charAt(i); if ((chr < "0" || chr > "9") && chr != ",") { //not digit or thousands separator result = false; break; }; if (i == 0 && (chr == "0" || chr == ",")) { //should not start with 0 or , result = false; break; }; }; return result; };
您可以在循环内添加其他条件,以满足您的特定需求。
将参数传递给构造函数时,可以使用的结果。
如果参数(字符串)不能转换为数字,则返回NaN,因此您可以确定所提供的字符串是否为有效数字。
注意:当传递空字符串或'\\t\\t'
和'\\n\\t'
作为数字时,将返回0; 传递true将返回1,而false则返回0。
Number('34.00') // 34 Number('-34') // -34 Number('123e5') // 12300000 Number('123e-5') // 0.00123 Number('999999999999') // 999999999999 Number('9999999999999999') // 10000000000000000 (integer accuracy up to 15 digit) Number('0xFF') // 255 Number('Infinity') // Infinity Number('34px') // NaN Number('xyz') // NaN Number('true') // NaN Number('false') // NaN // cavets Number(' ') // 0 Number('\t\t') // 0 Number('\n\t') // 0
我的尝试有些混乱,但不是最好的解决方案
function isInt(a){ return a === ""+~~a}console.log(isInt('abcd')); // falseconsole.log(isInt('123a')); // falseconsole.log(isInt('1')); // trueconsole.log(isInt('0')); // trueconsole.log(isInt('-0')); // falseconsole.log(isInt('01')); // falseconsole.log(isInt('10')); // trueconsole.log(isInt('-1234567890')); // trueconsole.log(isInt(1234)); // falseconsole.log(isInt('123.4')); // falseconsole.log(isInt('')); // false// other types then string returns falseconsole.log(isInt(5)); // falseconsole.log(isInt(undefined)); // falseconsole.log(isInt(null)); // falseconsole.log(isInt('0x1')); // falseconsole.log(isInt(Infinity)); // false
如果确实要确保字符串仅包含数字,任何数字(整数或浮点数)以及正好是数字, 则不能使用parseInt()
/ parseFloat()
, Number()
或!isNaN()
他们自己。 请注意,当Number()
返回数字时, !isNaN()
实际上返回true
,而当其返回NaN
时实际上返回false
,因此我将在其余的讨论中将其排除。
这个问题parseFloat()
是,它会返回一个数字,如果字符串中包含任何数量,即使字符串不只是和准确一些包含:
parseFloat("2016-12-31") // returns 2016parseFloat("1-1") // return 1parseFloat("1.2.3") // returns 1.2
Number()
的问题在于,如果传递的值根本不是数字,它将返回一个数字!
Number("") // returns 0Number(" ") // returns 0Number(" \u00A0 \t\n\r") // returns 0
滚动自己的正则表达式的问题在于,除非您创建了与浮点数匹配的确切正则表达式,否则Javascript会识别该正则表达式,否则您会错过某些情况,或者会发现本不应该的情况。 即使您可以使用自己的正则表达式,为什么呢? 有更简单的内置方法。
但是,事实证明,对于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))}
如果有人失望了,我会花一些时间来破解这个补丁,尝试对moment.js( )进行修补。 这是我从中拿走的东西:
function isNumeric(val) { var _val = +val; return (val !== val + 1) //infinity check && (_val === +val) //Cute coercion check && (typeof val !== 'object') //Array/object check}
处理以下情况:
真正! :
isNumeric("1"))isNumeric(1e10))isNumeric(1E10))isNumeric(+"6e4"))isNumeric("1.2222"))isNumeric("-1.2222"))isNumeric("-1.222200000000000000"))isNumeric("1.222200000000000000"))isNumeric(1))isNumeric(0))isNumeric(-0))isNumeric(1010010293029))isNumeric(1.100393830000))isNumeric(Math.LN2))isNumeric(Math.PI))isNumeric(5e10))
假! :
isNumeric(NaN))isNumeric(Infinity))isNumeric(-Infinity))isNumeric())isNumeric(undefined))isNumeric('[1,2,3]'))isNumeric({a:1,b:2}))isNumeric(null))isNumeric([1]))isNumeric(new Date()))
具有讽刺意味的是,我最努力的一个:
isNumeric(new Number(1)) => false
任何建议欢迎。 :]
也许有一个或两个遇到这个问题的人需要比平时更严格的检查(就像我一样)。 在这种情况下,这可能会很有用:
if(str === String(Number(str))) { // it's a "perfectly formatted" number}
谨防! 这将拒绝像琴弦.1
, 40.000
, 080
, 00.1
。 这非常挑剔-字符串必须与数字的“ 最最小完美形式 ”匹配,此测试才能通过。
它使用String
和Number
构造函数将字符串转换为数字,然后再次返回,从而检查JavaScript引擎的“完美最小形式”(使用初始Number
构造函数将其转换为最小形式)是否与原始字符串匹配。
我已经测试过,迈克尔的解决方案是最好的。 投票给他上面的答案(在该页面上搜索“如果您确实要确保该字符串”以找到它)。 本质上,他的答案是这样的:
function isNumeric(num){ num = "" + num; //coerce num to be a string return !isNaN(num) && !isNaN(parseFloat(num));}
它适用于每个测试用例,我在这里记录了这些内容: :
对于这些边缘情况,许多其他解决方案均失败:'',null,“”,true和[]。 从理论上讲,您可以通过适当的错误处理来使用它们,例如:
return !isNaN(num);
要么
return (+num === +num);
对/ \\ s /,null,“”,true,false,[](还有其他?)进行特殊处理
为什么jQuery的实现不够好?
function isNumeric(a) { var b = a && a.toString(); return !$.isArray(a) && b - parseFloat(b) + 1 >= 0;};
迈克尔提出了类似的建议(尽管我在这里偷了“ user1691651-约翰”的变更版):
function isNumeric(num){ num = "" + num; //coerce num to be a string return !isNaN(num) && !isNaN(parseFloat(num));}
以下是最有可能性能较差但结果稳定的解决方案。 这是jQuery 1.12.4实现和Michael的回答的矛盾之处,需要额外检查前导/后缀空格(因为Michael的版本对于前导/后缀空格的数字返回true):
function isNumeric(a) { var str = a + ""; var b = a && a.toString(); return !$.isArray(a) && b - parseFloat(b) + 1 >= 0 && !/^\s+|\s+$/g.test(str) && !isNaN(str) && !isNaN(parseFloat(str));};
不过,后一个版本具有两个新变量。 通过执行以下操作,可以绕开其中之一:
function isNumeric(a) { if ($.isArray(a)) return false; var b = a && a.toString(); a = a + ""; return b - parseFloat(b) + 1 >= 0 && !/^\s+|\s+$/g.test(a) && !isNaN(a) && !isNaN(parseFloat(a));};
除了手动测试我将在当前困境中遇到的几个用例(这都是非常标准的东西)以外,我还没有通过其他方式对这些中的任何一个进行过测试。 这是“站在巨人的肩膀上”的情况。
您可以像使用 y一样使用类型,以获取静态的编译时检查。 当然,对于用户输入而言并不是十分有用。
// @flowfunction acceptsNumber(value: number) { // ...}acceptsNumber(42); // Works!acceptsNumber(3.14); // Works!acceptsNumber(NaN); // Works!acceptsNumber(Infinity); // Works!acceptsNumber("foo"); // Error!
这是检查sNum
是否为有效数值的sNum
; 它已针对多种输入进行了测试:
!isNaN(+s.replace(/\s|\$/g, '')); // returns True if numeric value
我喜欢这个简单。
Number.isNaN(Number(value))
上面是普通的Javascript,但我将其与结合使用以进行智能类型检查。 这对于打字稿编译器为您提供正确的智能提示且没有类型错误非常有用。
isNotNumber(value: string | number): value is string { return Number.isNaN(Number(this.smartImageWidth));}isNumber(value: string | number): value is number { return Number.isNaN(Number(this.smartImageWidth)) === false;}
假设您的属性width
为number | string
number | string
。 您可能想根据是否为字符串来进行逻辑运算。
var width: number|string;width = "100vw";if (isNotNumber(width)) { // the compiler knows that width here must be a string if (width.endsWith('vw')) { // we have a 'width' such as 100vw } }else { // the compiler is smart and knows width here must be number var doubleWidth = width * 2; }
Typeguard足够聪明,可以将if
语句中的width
类型限制为ONLY string
。 这允许编译器允许width.endsWith(...)
,如果类型为string | number
不允许string | number
string | number
。
您可以将typeGuard命名为isNotNumber
, isNumber
, isString
, isNotString
但我认为isString
有点模棱两可且难以阅读。
我最近写了一篇有关确保变量为有效数字的方法的文章: : 本文介绍了如何确保浮点数或整数(如果是)重要( +x
vs ~~x
)。
本文假定变量是一个string
或number
开头,并且trim
可用/多填充。 同样,将其扩展为处理其他类型也不难。 这是它的实质:
// Check for a valid floatif (x == null || ("" + x).trim() === "" || isNaN(+x)) { return false; // not a float}// Check for a valid integerif (x == null || ("" + x).trim() === "" || ~~x !== +x) { return false; // not an integer}
这个问题的公认答案有很多缺陷(其他几个用户都强调了这一点)。 这是在javascript中解决该问题的最简单且经过验证的方法之一:
function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n);}
以下是一些好的测试用例:
console.log(isNumeric(12345678912345678912)); // trueconsole.log(isNumeric('2 ')); // trueconsole.log(isNumeric('-32.2 ')); // trueconsole.log(isNumeric(-32.2)); // trueconsole.log(isNumeric(undefined)); // false// the accepted answer fails at these tests:console.log(isNumeric('')); // falseconsole.log(isNumeric(null)); // falseconsole.log(isNumeric([])); // false
避免尝试查找“内置”解决方案的麻烦。
没有一个好的答案,并且在该线程中被高估的答案是错误的。
npm install is-number
在JavaScript中,可靠地检查值是否为数字并不总是那么简单。 开发人员通常使用+,-或Number()将字符串值转换为数字(例如,从用户输入,正则表达式匹配,解析器等返回值时)。 但是,有许多非直觉性的边缘案例会产生意想不到的结果:
console.log(+[]); //=> 0console.log(+''); //=> 0console.log(+' '); //=> 0console.log(typeof NaN); //=> 'number'
function isNumberCandidate(s) { const str = (''+ s).trim(); if (str.length === 0) return false; return !isNaN(+str);}console.log(isNumberCandidate('1')); // trueconsole.log(isNumberCandidate('a')); // falseconsole.log(isNumberCandidate('000')); // trueconsole.log(isNumberCandidate('1a')); // false console.log(isNumberCandidate('1e')); // falseconsole.log(isNumberCandidate('1e-1')); // trueconsole.log(isNumberCandidate('123.3')); // trueconsole.log(isNumberCandidate('')); // falseconsole.log(isNumberCandidate(' ')); // falseconsole.log(isNumberCandidate(1)); // trueconsole.log(isNumberCandidate(0)); // trueconsole.log(isNumberCandidate(NaN)); // falseconsole.log(isNumberCandidate(undefined)); // falseconsole.log(isNumberCandidate(null)); // falseconsole.log(isNumberCandidate(-1)); // trueconsole.log(isNumberCandidate('-1')); // trueconsole.log(isNumberCandidate('-1.2')); // trueconsole.log(isNumberCandidate(0.0000001)); // trueconsole.log(isNumberCandidate('0.0000001')); // trueconsole.log(isNumberCandidate(Infinity)); // trueconsole.log(isNumberCandidate(-Infinity)); // trueconsole.log(isNumberCandidate('Infinity')); // trueif (isNumberCandidate(s)) { // use +s as a number +s ...}
只需使用isNaN()
,它将把字符串转换成一个数字 ,如果得到一个有效的数字 ,将返回false
...
isNaN("Alireza"); //return trueisNaN("123"); //return false
我正在使用以下内容:
const isNumber = s => !isNaN(+s)
使用纯JavaScript:
Number.isNaN(Number('1')); // falseNumber.isNaN(Number('asdf')); // true
使用Lodash:
_.isNaN(_.toNumber('1')); // false_.isNaN(_.toNumber('asdf')); // true
对于TypeScript无效,因为:
declare function isNaN(number: number): boolean;
对于TypeScript,您可以使用:
/^\\d+$/.test(key)
这是isNumber实现的高性能版本(2.5 * 10 ^ 7迭代/ s @ 3.8GHz Haswell)。 它适用于我可以找到的每个测试用例(包括符号):
var isNumber = (function () { var isIntegerTest = /^\d+$/; var isDigitArray = [!0, !0, !0, !0, !0, !0, !0, !0, !0, !0]; function hasLeading0s (s) { return !(typeof s !== 'string' || s.length < 2 || s[0] !== '0' || !isDigitArray[s[1]] || isIntegerTest.test(s)); } var isWhiteSpaceTest = /\s/; return function isNumber (s) { var t = typeof s; var n; if (t === 'number') { return (s <= 0) || (s > 0); } else if (t === 'string') { n = +s; return !((!(n <= 0) && !(n > 0)) || n === '0' || hasLeading0s(s) || !(n !== 0 || !(s === '' || isWhiteSpaceTest.test(s)))); } else if (t === 'object') { return !(!(s instanceof Number) || ((n = +s), !(n <= 0) && !(n > 0))); } return false; };})();
也许这个问题已经被重复了很多次,但是我今天也与这个问题作斗争,并想发表我的答案,因为我没有看到任何其他答案能这么简单或彻底地做到这一点:
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 Casesconsole.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 Casesconsole.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
函数,并在这些用例中isNumeric
试,然后为所有用例扫描“ true”。
或者,查看每个返回的值:
好吧,我正在使用我制作的这个...
到目前为止,它一直在工作:
function checkNumber(value) { if ( value % 1 == 0 ) return true; else return false;}
如果您发现任何问题,请告诉我。
转载地址:http://mxogj.baihongyu.com/