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


当前回答

只需使用isNaN(),这将把字符串转换为数字,如果得到有效的数字,将返回false。。。

isNaN("Alireza"); //return true
isNaN("123"); //return false

其他回答

检查JS中的数字:

检查是否为数字的最佳方法:是有限的(20)//真的从字符串中读取值。CSS*:parseInt('2.5rem')//2parseFloat('2.5rem')//2.5 对于整数:isInteger(23/0)//错误如果值为NaN:isNaN(20)//错误

你可以按照RegExp的方式:

var num = "987238";

if(num.match(/^-?\d+$/)){
  //valid integer (positive or negative)
}else if(num.match(/^\d+\.\d+$/)){
  //valid float
}else{
  //not valid number
}

如果要查找正数(例如门牌号),请使用:

if (mystring > 0) ...

如果有人对此感到失望的话,我花了一些时间来修补moment.js(https://github.com/moment/moment). 我从中得到了一些东西:

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

欢迎提出任何建议。:]

测试字符串或数字是否为数字

const isNumeric = stringOrNumber =>
  stringOrNumber == 0 || !!+stringOrNumber;

或者如果要将字符串或数字转换为数字

const toNumber = stringOrNumber =>
  stringOrNumber == 0 || +stringOrNumber ? +stringOrNumber : NaN;