在javascript中进行类型检查


76

如何检查变量当前是否为整数类型?我一直在寻找某种资源,并且我认为===运算符很重要,但是我不确定如何检查变量是否为Integer(或与此相关的Array)


8
==检查值相等,===检查值和类型相等。“ 1” == 1将为真,“ 1” === 1将为假
Kai

您可以考虑使用像Not这样的很小的库。解决所有问题。
Calvintwr

Answers:


124

在JavaScript中,变量永远不会是整数类型-不能区分不同类型的Number。

您可以测试变量是否包含数字,以及该数字是否为整数。

(typeof foo === "number") && Math.floor(foo) === foo

如果变量可能是包含整数的字符串,并且您想查看情况是否如此:

foo == parseInt(foo, 10)

2
您还可以使用isNaN(foo)w3schools.com/jsref/jsref_NaN.asp代替typeof
m4tt1mus 2010年

4
“它不能区分不同类型的数字”是因为没有不同类型的数字。JS中的所有数值都是64位浮点数。
NullUserException 2012年

1
@NullUserException —这就是我所说的。
昆汀

如果您使用的是jQuery,则可以使用它的$ .type()函数。例如 $ .type(“ 1”)#=>“ string”
Andrei

2
由于与ECMAScript 2015 Number.isInteger函数不一致,因此应更新此答案。对于Infinity,它应该返回false ,而不是true。
RobG

15

如今,ECMAScript 6(ECMA-262)处于“内部”状态。用Number.isInteger(x)问你要问关于x的类型的问题:

js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false

7

如果数字的模%1为0-,则它是整数

function isInt(n){
    return (typeof n== 'number' && n%1== 0);
}

这只和javascript一样好-说+-到15号。

isInt(Math.pow(2,50)+.1)返回true,就像 Math.pow(2,50)+.1 == Math.pow(2,50)


0

我知道您对整数感兴趣,所以我不会回答,但是如果您想检查浮点数,可以这样做。

function isFloat( x )
{
    return ( typeof x === "number" && Math.abs( x % 1 ) > 0);
}

注意:这可以将以.0(或逻辑上等价0的)结尾的数字作为整数。在这种情况下,实际上需要发生浮点精度错误才能检测浮点值。

例如

alert(isFloat(5.2));   //returns true
alert(isFloat(5));     //returns false
alert(isFloat(5.0));   //return could be either true or false

0

诸如YourJS之类的一些实用程序库提供了一些函数来确定某物是数组还是某物是整数还是许多其他类型。YourJS通过检查值是否为数字然后被1整除来定义isInt

function isInt(x) {
  return typeOf(x, 'Number') && x % 1 == 0;
}

上面的代码段是从YourJS代码段中提取的,因此仅适用typeOf于该库,因为它是由库定义的。你可以下载YourJS的简约版本,主要只有类型检查的功能,例如typeOf()isInt()isArray()http://yourjs.com/snippets/build/34,2


0

您还可以看一下Runtyper,它是一种对===(和其他操作)操作数进行类型检查的工具。
对于你的榜样,如果有严格的比较x === yx = 123, y = "123",它会自动检查typeof x, typeof y并显示在控制台的警告:

严格比较不同类型:123(数字)===“ 123”(字符串)



0

干净的方法

您可以考虑使用非常小的无依赖库,例如Not。解决所有问题:

// at the basic level it supports primitives
let number = 10
let array = []
not('number', 10) // returns false
not('number', []) // throws error

// so you need to define your own:
let not = Object.create(Not)

not.defineType({
    primitive: 'number',
    type: 'integer',
    pass: function(candidate) {
        // pre-ECMA6
        return candidate.toFixed(0) === candidate.toString()
        // ECMA6
        return Number.isInteger(candidate)
    }
})
not.not('integer', 4.4) // gives error message
not.is('integer', 4.4) // returns false
not.is('integer', 8) // returns true

如果养成习惯,您的代码将更强大。Typescript解决了部分问题,但在运行时不起作用,这也很重要。

function test (string, boolean) {
    // any of these below will throw errors to protect you
    not('string', string)
    not('boolean', boolean)

    // continue with your code.
}

1
您能否解释一下使用这种技术如何检查某物是否为整数?
sova

@sova我已经添加了示例。
Calvintwr
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.