在javascript中键入检查

时间:2010-12-22 23:18:23

标签: javascript types

如何检查变量当前是否为整数类型?我已经为此寻找了某种资源,我认为===运算符很重要,但我不确定如何检查变量是否为整数(或者是一个数组)

8 个答案:

答案 0 :(得分:110)

变量永远不会是JavaScript中的整数类型 - 它不区分不同类型的数字。

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

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

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

foo == parseInt(foo, 10)

答案 1 :(得分:11)

这些天,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

答案 2 :(得分:6)

如果数字的模数%1为0 -

,则数字为整数
function isInt(n){
    return (typeof n== 'number' && n%1== 0);
}

这只有javascript得到 - 比如说+ - 十到十五。

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

答案 3 :(得分:0)

试试这段代码:

 alert(typeof(1) == "number");

答案 4 :(得分:0)

我知道你对Integer数字很感兴趣所以我不会回答这个问题,但如果你想检查浮点数,你可以这样做。

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

注意:这可以将以.0结尾的数字(或任何逻辑等效数量的0)视为INTEGER。在这种情况下,实际上需要发生浮点精度误差来检测浮点值。

实施例

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

答案 5 :(得分:0)

相当多的实用程序库(如YourJS)提供了用于确定某些内容是否为数组或者某些内容是整数还是许多其他类型的函数。 YourJS通过检查值是否为数字来定义isInt,然后是否可以被1整除:

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

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

答案 6 :(得分:0)

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

  

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

答案 7 :(得分: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.
}
相关问题