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 Code code as follows:
function Isnumber (obj) {
return typeof obj = = ' number '
}
This function is not a problem for integers and floating-point numbers, but returns true for Nan values. It's a bit of a bad thing, after all, with isnumber judgment, no one will use Nan to do arithmetic.
Then improve it and try it with Object.prototype.toString.
Copy Code code as follows:
function Isnumber (obj) {
return Object.prototype.toString.call (obj) = = ' [Object number] '
}
As with typeof, it returns true for Nan, and the amount of code is large, which is not the desired result. Tostring.call Way to judge arrays (array) feasible, the number is powerless.
Again, the Nan value is dealt with by the isNaN function.
Copy Code code as follows:
function Isnumber (obj) {
return typeof obj = = ' number ' &&!isnan (obj)
}
This time, if the incoming non-numeric (Nan or a value that can be converted to Nan) returns false
Copy Code code 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 an equivalence, with isfinite to judge
Copy Code code as follows:
function Isnumber (obj) {
return typeof obj = = ' number ' && isfinite (obj)
}
Up to now, the digital judgment of the shortest code is the third one mentioned in this article that uses the isNaN function. The following grand launch of the world's shortest digital judgment code
Copy Code code as follows:
function Isnumber (obj) {
return obj = = +obj
}
For integers, the floating-point number returns true and False for Nan or a value that can be converted to Nan.
You don't understand, do you? Goo ~ ~ (╯﹏╰)
Park friends say this is not the world's shortest Judgment number code, parameter obj can be changed to a character. (⊙o⊙) you are right.
Extrapolate, similar to the use of JS Dynamic language characteristics (operator operation when the internal automatic type conversion) the shortest judgment and.
Copy Code code as follows:
Judgment string
function isstring (obj) {
return obj = = obj+ '
}
To judge a Boolean type
function Isboolean (obj) {
return obj = = =!! Obj
}