Home > Web Front-end > JS Tutorial > The simplest implementation method to determine the type of integer in JavaScript

The simplest implementation method to determine the type of integer in JavaScript

高洛峰
Release: 2016-11-02 10:23:57
Original
1131 people have browsed it

We know that JavaScript provides the typeof operator, so the easiest thing to think of is to use typeof to determine whether it is a number type.

Copy the code as follows:

function isNumber(obj) {
    return typeof obj === 'number'
}
Copy after login

This function has no problem with integers and floating point numbers, but it also returns true for NaN values, which makes people feel uncomfortable. After all, no one will use NaN after using isNumber to judge. Arithmetic operations.

Then improve it and try using Object.prototype.toString.

Copy code code is as follows:

function isNumber(obj) {  
  return Object.prototype.toString.call(obj) === '[object Number]'
  }
Copy after login

This time, if the input is a non-number (NaN or a value that can be converted to NaN), false will be returned

Copy code code is as follows:

function isNumber(obj) {
    return typeof obj === 'number' && !isNaN(obj)
}
isNumber(1)   // true
isNumber(1.2) // true
isNumber(NaN) // false
isNumber( parseInt('a') ) // false
Copy after login

Well, this isNumber is good, but there is an equivalent one, use isFinite to judge

Copy the code as follows:

function isNumber(obj) {
    return typeof obj === 'number' && isFinite(obj)   
}
Copy after login

Up to now, the shortest code for numeric judgment is the third one mentioned in this article that uses the isNaN function. Here is the world's shortest digital judgment web code

Copy the code as follows:

function isNumber(obj) {
    return obj === +obj
}
Copy after login

Returns true for integers and floating point numbers, and returns false for NaN or values ​​that can be converted to NaN.

You don’t understand? Gu~~(╯﹏╰)

Garden friends said that this is not the shortest judgment numeric code in the world, and the parameter obj can be changed to one character. (⊙o⊙) You are right.

By analogy, there is a similar shortest judgment using JS dynamic language features (automatic internal type conversion during operator operation).

Copy the code code as follows:

// 判断字符串
function isString(obj) {
    return obj === obj+''
}
// 判断布尔类型
function isBoolean(obj) {
    return obj === !!obj
}
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template