The simplest way to determine the type of a whole word in JavaScript

  • 2020-03-30 04:13:56
  • OfStack

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.


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

This function has no problem with integers or floating point Numbers, but it also returns true for NaN values, which is annoying because no one will use NaN to do arithmetic after isNumber passes.

The improvement, with the Object. The prototype. Try the toString.


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

As with the typeof judgment, true is also returned for NaN, which is too much code, which is not the desired result. The tostring.call method determines that the Array is ok, but the Numbers are not.

Better yet, the NaN value is handled by the isNaN function.


function isNumber(obj) {
    return typeof obj === 'number' && !isNaN(obj)
}

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


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

Well, this is a good isNumber, but there's an equivalent, isFinite


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

So far, the number determination for the shortest code is the third one mentioned in this article that USES the isNaN function. Here's the world's shortest code for judging Numbers


function isNumber(obj) {
    return obj === +obj
}

For integers, floating-point Numbers return true, and false for NaN or values that can be converted to NaN.

I don't understand, do I? Goo ~ ~ ( � � � )

Friends of the park said that this is not the world's shortest judge numeric code, the parameter obj can be changed to a character. You're right.

Similarly, the JS dynamic language feature (internal automatic type conversion during operator operation) is used to determine the shortest.


//Determine the string
function isString(obj) {
    return obj === obj+''
}
//Determine the Boolean type < br / > function isBoolean(obj) {
    return obj === !!obj
}


Related articles: