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


当前回答

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

if (mystring > 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)],我无法对此进行说明,但这正是我们所需要的。

如果有人对此感到失望的话,我花了一些时间来修补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

欢迎提出任何建议。:]

typeof运算符返回一个字符串,指示操作数值的类型。

对于number,它返回“number”字符串。

function isNumber(num) {
   return typeof num === "number";
}

您也可以使用简单的parseInt函数。。。带有if条件例如

if (parseInt(i)){
    (i in dic) ? dic[i] += 1 : dic[i] = 1
}

省去了寻找“内置”解决方案的麻烦。

没有一个好的答案,而这篇文章中获得极大支持的答案是错误的。

npm安装是数字

在JavaScript中,可靠地检查值是否为数字并不总是那么简单。开发人员通常使用+、-或Number()将字符串值转换为数字(例如,当从用户输入、正则表达式匹配、解析器等返回值时)。但有许多非直觉的边缘情况会产生意想不到的结果:

console.log(+[]); //=> 0
console.log(+''); //=> 0
console.log(+'   '); //=> 0
console.log(typeof NaN); //=> 'number'