We know that JavaScript provides typeof operator, so the easiest thing to think of is to use typeof to determine whether it is of number type.
The code copy is as follows:
function isNumber(obj) {
return typeof obj === 'number'
}
This function has no problem with integers and floating-point numbers, but it also returns true for NaN value, which makes people feel uncomfortable. After all, no one will use NaN to do arithmetic operations after using isNumber to judge.
Then improve it and try using Object.prototype.toString.
The code copy is as follows:
function isNumber(obj) {
return Object.prototype.toString.call(obj) === '[object Number]'
}
Like typeof judgment, it also returns true for NaN, and the amount of code is still large, which is not the desired result. ToString.call method determines that array (Array) is feasible, but numbers are out of reach.
After further improvement, the NaN value isNaN function to deal with.
The code copy is as follows:
function isNumber(obj) {
return typeof obj === 'number' && !isNaN(obj)
}
This time, if the incoming number is a non-number (NaN or a value that can be converted to NaN), it will return false.
The code copy 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
Well, this isNumber is good, but there is another equivalent, use isFinite to judge
The code copy is as follows:
function isNumber(obj) {
return typeof obj === 'number' && isFinite(obj)
}
Up to now, the numerical judgment of the shortest code is the third one mentioned in this article that uses the isNaN function. The world's shortest numerical judgment code is launched below
The code copy is as follows:
function isNumber(obj) {
return obj === +obj
}
For integers, the floating point number returns true, and for NaN or values that can be converted to NaN, false.
Don't understand, right? Gu~~()
Gardeners said that this is not the shortest numerical code in the world, and the parameter obj can be changed to one character. (⊙o⊙) You are right.
Learn from one example and the shortest judgment is also given to the shortest use of JS dynamic language features (internal automatic type conversion when operator operation).
The code copy is as follows:
// Judge string
function isString(obj) {
return obj === obj+''
}
//Judge boolean type
function isBoolean(obj) {
return obj === !!obj
}