The simplest implementation method for determining the font type in JavaScript, And the javascript font type
We know that JavaScript provides the typeof operator, so it is most likely to use typeof to determine whether it is a number type.
Copy codeThe Code is as follows:
Function isNumber (obj ){
Return typeof obj = 'number'
}
This function is no problem for integers and floating-point numbers, but it is uncomfortable to return true for NaN values. After all, no one will use NaN for arithmetic operations after isNumber is used to determine the result.
Try Object. prototype. toString.
Copy codeThe Code is as follows:
Function isNumber (obj ){
Return Object. prototype. toString. call (obj) = '[object Number]'
}
Like typeof, true is returned for NaN, and the amount of code is large. This is not the desired result. The toString. call method is used to determine whether an Array (Array) is feasible, while the number is insufficient.
Then, the NaN value is dealt with using the isNaN function.
Copy codeThe Code is as follows:
Function isNumber (obj ){
Return typeof obj = 'number '&&! IsNaN (obj)
}
This time, if the input is not a number (NaN or can be converted to NaN value), false is returned.
Copy codeThe 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
Well, this isNumber is good, but there is another equivalent, which can be determined by isFinite.
Copy codeThe Code is as follows:
Function isNumber (obj ){
Return typeof obj = 'number' & isFinite (obj)
}
Up to now, the number of the shortest code is determined by the third isNaN function mentioned in this article. Next we will introduce the world's shortest digital judgment code
Copy codeThe Code is as follows:
Function isNumber (obj ){
Return obj = + obj
}
For integers, the floating point returns true, and the return value is false for NaN or NaN values that can be converted to NaN values.
Didn't you understand it, did you? Cool ~~ (Too many rows)
Yuan You said that this is not the world's shortest digital code, the parameter obj can be changed to a character. You are right.
Similar to the use of JS dynamic language features (internal automatic type conversion during operator operations.
Copy codeThe Code is as follows:
// Judge the string
Function isString (obj ){
Return obj = obj +''
}
// Determine the Boolean Type
Function isBoolean (obj ){
Return obj = !! Obj
}