我希望在与旧的VB6 IsNumeric()函数相同的概念空间中有什么东西?
当前回答
报价:
isNaN(num)//如果变量不包含有效数字,则返回true
如果您需要检查前导/尾随空格,则不完全正确-例如,当需要一定数量的数字时,并且您需要获得例如“1111”而不是“111”或“111”以获得PIN输入。
更好使用:
var num = /^\d+$/.test(num)
其他回答
我喜欢这种简单。
Number.isNaN(Number(value))
以上是常规的Javascript,但我将其与typescript类型保护器一起用于智能类型检查。这对于类型脚本编译器提供正确的智能感知和无类型错误非常有用。
打字保护装置
警告:请参阅Jeremy在下面的评论。这在某些值上有一些问题,我现在没有时间修复它,但使用typescript类型保护的想法很有用,因此我不会删除此部分。
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;
}
假设您有一个属性宽度,即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;
}
类型保护足够聪明,可以将if语句中的宽度类型限制为ONLY字符串。这允许编译器允许width.endsWith(…),如果类型为string | number,则不允许。
你可以随意调用类型保护器isNotNumber,isNumber,isString,isNotString,但我认为isString有点模棱两可,很难理解。
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
如果您真的想确保字符串只包含一个数字、任何数字(整数或浮点)以及一个数字,则不能使用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))
}
它对TypeScript无效,因为:
声明函数isNaN(数字:数字):布尔值;
对于TypeScript,您可以使用:
/^\d+$/.测试(键)
如果您只是想检查字符串是否为整数(无小数位数),正则表达式是一个很好的方法。其他方法(如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
推荐文章
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数
- 如何在JavaScript中转义单引号(')?
- Ng-repeat结束事件
- 谷歌MAP API未捕获的类型错误:无法读取属性“offsetWidth”为空
- 模糊vs聚焦-有什么真正的区别吗?
- 如何使用JavaScript创建和样式一个div ?
- 清除JavaScript中的缓存