简体   繁体   English

在javascript中进行类型检查

[英]type checking in javascript

How can I check if a variable is currently an integer type?如何检查变量当前是否为整数类型? I've looked for some sort of resource for this and I think the === operator is important, but I'm not sure how to check if a variable is an Integer (or an Array for that matter)我为此寻找了某种资源,我认为 === 运算符很重要,但我不确定如何检查变量是否为整数(或数组)

A variable will never be an integer type in JavaScript — it doesn't distinguish between different types of Number.在 JavaScript 中,变量永远不会是整数类型——它不区分不同类型的 Number。

You can test if the variable contains a number, and if that number is an integer.您可以测试变量是否包含数字,以及该数字是否为整数。

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

If the variable might be a string containing an integer and you want to see if that is the case:如果变量可能是一个包含整数的字符串,而您想查看是否是这种情况:

foo == parseInt(foo, 10)

These days, ECMAScript 6 (ECMA-262) is "in the house".这些天来,ECMAScript 6 (ECMA-262) 已经“在家里”了。 Use Number.isInteger(x) to ask the question you want to ask with respect to the type of x:使用Number.isInteger(x)来询问关于 x 类型的问题:

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

A number is an integer if its modulo %1 is 0-如果一个数的模 %1 是 0- 则它是一个整数

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

This is only as good as javascript gets- say +- ten to the 15th.这仅与 javascript 一样好 - 比如说 +- 10 到 15。

isInt(Math.pow(2,50)+.1) returns true , as does Math.pow(2,50)+.1 == Math.pow(2,50) isInt(Math.pow(2,50)+.1)返回trueMath.pow(2,50)+.1 == Math.pow(2,50)也是如此

A clean approach一个干净的方法

You can consider using a very small, dependency-free library like Issable .您可以考虑使用非常小的、无依赖性的库,例如Issable Solves all problems:解决所有问题:

// at the basic level it supports primitives
let number = 10
let array = []
is(number).number() // returns true
is(array).number() // throws error

// so you need to define your own:
import { define } from 'issable'
// or require syntax
const { define } = require('issable')

define({
    primitives: 'number',
    nameOfTyping: 'integer',
    toPass: function(candidate) {
        // pre-ECMA6
        return candidate.toFixed(0) === candidate.toString()
        // ECMA6
        return Number.isInteger(candidate)
    }
})
is(4.4).custom('integer') // throws error
is(8).customer('integer') // returns true

If you make it a habit, your code will be much stronger.如果你养成习惯,你的代码会更强大。 Typescript solves part of the problem but doesn't work at runtime, which is also important. Typescript 解决了部分问题,但在运行时不起作用,这也很重要。

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

    // continue with your code.
}

I know you're interested in Integer numbers so I won't re answer that but if you ever wanted to check for Floating Point numbers you could do this.我知道你对整数感兴趣,所以我不会再回答这个问题,但如果你想检查浮点数,你可以这样做。

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

Note: This MAY treat numbers ending in .0 (or any logically equivalent number of 0 's) as an INTEGER.注意:这可以将以.0结尾的数字(或任何逻辑上等效的0数)视为整数。 It actually needs a floating point precision error to occur to detect the floating point values in that case.在这种情况下,它实际上需要发生浮点精度错误来检测浮点值。

Ex.前任。

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

Quite a few utility libraries such as YourJS offer functions for determining if something is an array or if something is an integer or a lot of other types as well.相当多的实用程序库(例如YourJS)提供了用于确定某物是数组还是整数或许多其他类型的函数。 YourJS defines isInt by checking if the value is a number and then if it is divisible by 1: YourJS通过检查值是否为数字然后检查它是否可被 1 整除来定义 isInt:

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

The above snippet was taken from this YourJS snippet and thusly only works because typeOf is defined by the library.上面的代码片段取自这个 YourJS 代码片段,因此只能工作,因为typeOf是由库定义的。 You can download a minimalistic version of YourJS which mainly only has type checking functions such as typeOf() , isInt() and isArray() : http://yourjs.com/snippets/build/34,2您可以下载 YourJS 的简约版本,它主要只有类型检查功能,例如typeOf()isInt()isArray() :http: //yourjs.com/snippets/build/34,2

You may also have a look on Runtyper - a tool that performs type checking of operands in === (and other operations).您还可以查看Runtyper——一种对=== (和其他操作)中的操作数执行类型检查的工具。
For your example, if you have strict comparison x === y and x = 123, y = "123" , it will automatically check typeof x, typeof y and show warning in console:对于您的示例,如果您对x === yx = 123, y = "123"进行严格比较,它将自动检查typeof x, typeof y并在控制台中显示警告:

Strict compare of different types: 123 (number) === "123" (string)不同类型的严格比较:123(数字)===“123”(字符串)

Try this code:试试这个代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM