js 判断是不是 整数

代码;数组

这篇看看如何判断为整数类型(Integer),JavaScript中不区分整数和浮点数,全部数字内部都采用64位浮点格式表示,和Java的double类型同样。但实际操做中好比数组索引、位操做则是基于32位整数。
方式1、使用取余运算符判断
任何整数都会被1整除,即余数是0。利用这个规则来判断是不是整数。
?
1
2
3
4
5
function isInteger(obj) {
 return obj%1 === 0
}
isInteger(3) // true
isInteger(3.3) // false 
以上输出能够看出这个函数挺好用,但对于字符串和某些特殊值显得力不从心
?
1
2
3
4
isInteger('') // true
isInteger('3') // true
isInteger(true) // true
isInteger([]) // true
对于空字符串、字符串类型数字、布尔true、空数组都返回了true,真是难以接受。对这些类型的内部转换细节感兴趣的请参考:JavaScript中奇葩的假值
所以,须要先判断下对象是不是数字,好比加一个typeof
?
1
2
3
4
5
6
7
function isInteger(obj) {
 return typeof obj === 'number' && obj%1 === 0
}
isInteger('') // false
isInteger('3') // false
isInteger(true) // false
isInteger([]) // false
嗯,这样比较完美了。
方式2、使用Math.round、Math.ceil、Math.floor判断
整数取整后仍是等于本身。利用这个特性来判断是不是整数,Math.floor示例,以下
?
1
2
3
4
5
6
7
8
9
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
这个直接把字符串,true,[]屏蔽了,代码量比上一个函数还少。
方式3、经过parseInt判断
?
1
2
3
4
5
6
7
8
9
function isInteger(obj) {
 return parseInt(obj, 10) === obj
}
isInteger(3) // true
isInteger(3.3) // false
isInteger('') // false
isInteger('3') // false
isInteger(true) // false
isInteger([]) // false
很不错,但也有一个缺点
?
1
isInteger(1000000000000000000000) // false
居然返回了false,没天理啊。缘由是parseInt在解析整数以前强迫将第一个参数解析成字符串。这种方法将数字转换成整型不是一个好的选择。 
方式4、经过位运算判断
?
1
2
3
4
5
6
7
8
9
function isInteger(obj) {
 return (obj | 0) === obj
}
isInteger(3) // true
isInteger(3.3) // false
isInteger('') // false
isInteger('3') // false
isInteger(true) // false
isInteger([]) // false
这个函数很不错,效率还很高。但有个缺陷,上文提到过,位运算只能处理32位之内的数字,对于超过32位的无能为力,如
复制代码 代码以下:
isInteger(Math.pow(2, 32)) // 32位以上的数字返回false了

固然,多数时候咱们不会用到那么大的数字。
方式5、ES6提供了Number.isInteger
?
1
2
3
4
5
6
Number.isInteger(3) // true
Number.isInteger(3.1) // false
Number.isInteger('') // false
Number.isInteger('3') // false
Number.isInteger(true) // false
Number.isInteger([]) // false
目前,最新的Firefox和Chrome已经支持。


此外咱们须要判断是否 数字 还能够 加上: 使用  isNaN  结合上面的 便可 判断是否 数字了。
  if ((score) && (weight) && (!isNaN(score)) && (score >= 0 && score <= 100)) {
}

或者使用正则: > http://blog.csdn.net/l912943297/article/details/53993845函数

相关文章
相关标签/搜索