Method one, using the remainder operator to judge
Any integer will be divisible by 1, that is, the remainder is 0. Use this rule to determine whether an integer.
function Isinteger (obj) {
return obj%1 = = 0
}
Isinteger (3)//True
Isinteger (3.3)//False
The above output can see that this function is very useful, but for strings and some special values appear powerless
Isinteger (')//True
Isinteger (' 3 ')//True
Isinteger (TRUE)//True
Isinteger ([])//True
It is difficult to accept the return of true for an empty string, a string type number, a Boolean true, or an empty array. Please refer to these types of internal conversion details: The false value of the wonderful flowers in JavaScript
Therefore, you need to first determine whether the object is a number, such as adding a typeof
function Isinteger (obj) {
return typeof obj = = ' number ' && obj%1 = 0
}
Isinteger (')//False
Isinteger (' 3 ')//False
Isinteger (True)//False
Isinteger ([])//False
Well, it's perfect.
Second, the use of Math.Round, Math.ceil, Math.floor judgment
Integers are equal to themselves after rounding. Use this feature to determine whether an integer, math.floor example, as follows
function Isinteger (obj) {
return Math.floor (obj) = = obj
}
Isinteger (3)//True
Isinteger (3.3)//False
Isinteger (')//False
Isinteger (' 3 ')//False
Isinteger (True)//False
Isinteger ([])//False
This directly masks the string, true,[], with less code than the previous function.
Third, through parseint judgment
function Isinteger (obj) {
return parseint (obj, ten) = = obj
}
Isinteger (3)//True
Isinteger (3.3)//False
Isinteger (')//False
Isinteger (' 3 ')//False
Isinteger (True)//False
Isinteger ([])//False
It's good, but there's one drawback.
Isinteger (1000000000000000000000)//False
Actually returned false, no justice. The reason is that parseint forces the first parameter to be parsed into a string before parsing the integer. This method of converting numbers to integers is not a good choice.
Four, through the position operation judgment
function Isinteger (obj) {
Return (obj 0) = = obj
}
Isinteger (3)//True
Isinteger (3.3)//False
Isinteger (')//False
Isinteger (' 3 ')//False
Isinteger (True)//False
Isinteger ([])//False
This function is very good, the efficiency is very high. But there is a flaw, mentioned above, the bitwise operation can only deal with the number of 32 digits, for more than 32-bit powerless, such as
1 |
isInteger(Math.pow(2, 32)) // 32位以上的数字返回false了 |
Of course, most of the time we don't use that big number.
V. ES6 provided the Number.isinteger
Number.isinteger (3)//True
Number.isinteger (3.1)//False
Number.isinteger (')//False
Number.isinteger (' 3 ')//False
Number.isinteger (True)//False
Number.isinteger ([])//False