我希望在与旧的VB6 IsNumeric()函数相同的概念空间中有什么东西?
当前回答
我喜欢这种简单。
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有点模棱两可,很难理解。
其他回答
我在用我做的这个。。。
到目前为止,它一直在发挥作用:
function checkNumber(value) {
return value % 1 == 0;
}
如果你发现它有任何问题,请告诉我。
在我的应用程序中,我们只允许a-z a-z和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)],我无法对此进行说明,但这正是我们所需要的。
只需使用isNaN(),这将把字符串转换为数字,如果得到有效的数字,将返回false。。。
isNaN("Alireza"); //return true
isNaN("123"); //return false
我使用的是:
const isNumber = s => !isNaN(+s)
以下内容如何?
const a = '1'
const isNumber = (a) => Number(a) === +a
推荐文章
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置