我希望在与旧的VB6 IsNumeric()函数相同的概念空间中有什么东西?
当前回答
只需使用isNaN(),这将把字符串转换为数字,如果得到有效的数字,将返回false。。。
isNaN("Alireza"); //return true
isNaN("123"); //return false
其他回答
我的尝试有点混乱,Pherhaps不是最好的解决方案
function isInt(a){
return a === ""+~~a
}
console.log(isInt('abcd')); // false
console.log(isInt('123a')); // false
console.log(isInt('1')); // true
console.log(isInt('0')); // true
console.log(isInt('-0')); // false
console.log(isInt('01')); // false
console.log(isInt('10')); // true
console.log(isInt('-1234567890')); // true
console.log(isInt(1234)); // false
console.log(isInt('123.4')); // false
console.log(isInt('')); // false
// other types then string returns false
console.log(isInt(5)); // false
console.log(isInt(undefined)); // false
console.log(isInt(null)); // false
console.log(isInt('0x1')); // false
console.log(isInt(Infinity)); // false
我最近写了一篇关于如何确保变量是有效数字的文章:https://github.com/jehugaleahsa/artifacts/blob/master/2018/typescript_num_hack.md本文解释了如何确保浮点或整数,如果这很重要(+x vs ~~x)。
本文假设变量是一个字符串或一个数字开头,trim可用/polyfulled。将其扩展到处理其他类型也不难。这是它的肉:
// Check for a valid float
if (x == null
|| ("" + x).trim() === ""
|| isNaN(+x)) {
return false; // not a float
}
// Check for a valid integer
if (x == null
|| ("" + x).trim() === ""
|| ~~x !== +x) {
return false; // not an integer
}
您也可以使用简单的parseInt函数。。。带有if条件例如
if (parseInt(i)){
(i in dic) ? dic[i] += 1 : dic[i] = 1
}
这样对我来说很有用。
function isNumeric(num){
let value1 = num.toString();
let value2 = parseFloat(num).toString();
return (value1 === value2);
}
console.log(
isNumeric(123), //true
isNumeric(-123), //true
isNumeric('123'), //true
isNumeric('-123'), //true
isNumeric(12.2), //true
isNumeric(-12.2), //true
isNumeric('12.2'), //true
isNumeric('-12.2'), //true
isNumeric('a123'), //false
isNumeric('123a'), //false
isNumeric(' 123'), //false
isNumeric('123 '), //false
isNumeric('a12.2'), //false
isNumeric('12.2a'), //false
isNumeric(' 12.2'), //false
isNumeric('12.2 '), //false
)
我是这样做的:
function isString(value)
{
return value.length !== undefined;
}
function isNumber(value)
{
return value.NaN !== undefined;
}
当然,如果您传递其他定义了“length”的对象,isString()将在这里出错。
推荐文章
- 如何在单个测试基础上更改模拟实现?
- VueJS有条件地为元素添加属性
- Uncaught TypeError:(中间值)(…)不是一个函数
- 如何设置URL查询参数在Vue与Vue路由器
- 无法读取属性“addEventListener”为空
- 如何防止moment.js从webpack加载地区?
- getMonth在javascript中给出前一个月
- 如何在禁用按钮上启用引导工具提示?
- Node.js全局变量
- 在前一个函数完成后调用另一个函数
- JavaScript中两个日期之间的月份差异
- 如何同时运行两个jQuery动画?
- 如何将FormData (HTML5对象)转换为JSON
- Object.hasOwnProperty()产生ESLint 'no-prototype-builtins'错误:如何修复?
- 如何将Node.js流的内容读入字符串变量?