如何在节点JS中检查数据类型 - 特别是整数

how to check for datatype in node js- specifically for integer

本文关键字:数据类型 特别是 整数 检查 节点 JS      更新时间:2023-09-26

我尝试了以下内容来检查数据类型(特别是整数(,但不起作用。

var i = "5";
if(Number(i) = 'NaN')
{
 console.log('This is not number'));
}

我想到两种方法来测试值的类型:

方法一:

您可以使用 isNaN javascript 方法,该方法确定值是否为 NaN。但是因为在你的情况下,你正在测试一个转换为字符串的数值,Javascript 试图猜测值的类型并将其转换为数字 5,这不是NaN。这就是为什么如果你console.log出结果,你会惊讶于代码:

if (isNaN(i)) {
    console.log('This is not number');
}

不会返回任何东西。因此,更好的替代方法是方法 2。

方法2:

您可以使用javascript typeof方法来测试变量或值的类型

if (typeof i != "number") {
    console.log('This is not number');
}

请注意,我使用的是双等运算符,因为在这种情况下,值的类型是一个字符串,但 Javascript 内部将转换为 Number。

强制值为数值类型的更健壮的方法是使用 Number.isNaN,它是新 Ecmascript 6(和谐(提案的一部分,因此不广泛且得到不同供应商的完全支持。

我以这种方式使用它并且工作正常

quantity=prompt("Please enter the quantity","1");
quantity=parseInt(quantity);
if (!isNaN( quantity ))
{
    totalAmount=itemPrice*quantity;
}
return totalAmount;

我刚刚在node.js v4.2.4中做了一些测试(但这在任何javascript实现中都是如此(:

> typeof NaN
'number'
> isNaN(NaN)
true
> isNaN("hello")
true

令人惊讶的是第一个,因为NaN的类型是"数字",但这就是JavaScript中定义它的方式。

所以下一个测试会带来意想不到的结果

> typeof Number("hello")
"number"

因为数字("hello"(是 NaN

以下函数按预期生成结果:

function isNumeric(n){
  return (typeof n == "number" && !isNaN(n));
}

你的逻辑是正确的,但你有 2 个错误,显然每个人都错过了:

只需将if(Number(i) = 'NaN')更改为if(Number(i) == NaN)

NaN是一个常量,您应该使用等号进行比较,单个等号用于为变量赋值。

你可以试试这个isNaN(Number(x))其中 x 是字符串或数字等任何内容

您可以通过检查其构造函数来检查您的数字。

var i = "5";
if( i.constructor !== Number )
{
 console.log('This is not number'));
}

如果你想知道 "1" ou 1 是否可以转换为数字,你可以使用以下代码:

if (isNaN(i*1)) {
     console.log('i is not a number'); 
}

var val = ... //the value you want to check
if(Number.isNaN(Number(val))){
  console.log("This is NOT a number!");
}else{
  console.log("This IS a number!");
}

如果使用节点 12,则可以使用

Number.isInteger(..)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger