This article mainly introduces the most concise implementation method for determining the entire word type in JavaScript. This article provides multiple methods for determining integers, and finally summarizes a shortest and simplest implementation method, if you need the typeof operator, you can refer to the following: we know that JavaScript provides the typeof operator, so it is most likely to use typeof to determine whether it is a number type.
The 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.
The Code is as follows:
function isNumber(obj) { return Object.prototype.toString.call(obj) === '[object Number]' }
This time, if the input is not a number (NaN or can be converted to NaN value), false is returned.
The Code is as follows:
function isNumber(obj) { return typeof obj === 'number' && !isNaN(obj)}isNumber(1) // trueisNumber(1.2) // trueisNumber(NaN) // falseisNumber( parseInt('a') ) // false
Well, this isNumber is good, but there is another equivalent, which can be determined by isFinite.
The 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. The following is a grand introduction of the world's shortest digital judgment Web Page code
The 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.
The Code is as follows:
// Judge the string function isString (obj) {return obj = obj + ''} // judge the Boolean Type function isBoolean (obj) {return obj = !! Obj}