JavaScript中判断为整数的多种方式

来源:互联网 发布:directx游戏编程 编辑:程序博客网 时间:2024/06/05 07:03
 JavaScript中不区分整数和浮点数,所有数字内部都采用64位浮点格式表示。但实际操作中比如数组索引、位操作则是基于32位整数。

方式一、使用取余运算符判断

       任何整数都会被1整除,即余数是0。利用这个规则来判断是否是整数。

  1. function isInteger(obj) {
  2.     return obj%1 === 0
  3. }
  4. isInteger(3) // true
  5. isInteger(3.3) // false  
复制代码

       以上输出可以看出这个函数挺好用,但对于字符串和某些特殊值显得力不从心
  1. isInteger('') // true
  2. isInteger('3') // true
  3. isInteger(true) // true
  4. isInteger([]) // true
复制代码

       对于空字符串、字符串类型数字、布尔true、空数组都返回了true,真是难以接受。对这些类型的内部转换细节感兴趣的请参考:JavaScript中奇葩的假值

       因此,需要先判断下对象是否是数字,比如加一个typeof

  1. function isInteger(obj) {

  2.     return typeof obj === 'number' && obj%1 === 0

  3. }

  4. isInteger('') // false

  5. isInteger('3') // false

  6. isInteger(true) // false

  7. isInteger([]) // false
复制代码

       嗯,这样比较完美了。

二、使用Math.round、Math.ceil、Math.floor判断

       整数取整后还是等于自己。利用这个特性来判断是否是整数,Math.floor示例,如下

  1. function isInteger(obj) {

  2.     return Math.floor(obj) === obj

  3. }

  4. isInteger(3) // true

  5. isInteger(3.3) // false

  6. isInteger('') // false

  7. isInteger('3') // false

  8. isInteger(true) // false

  9. isInteger([]) // false
复制代码

       这个直接把字符串,true,[]屏蔽了,代码量比上一个函数还少。

三、通过parseInt判断

  1. function isInteger(obj) {

  2.     return parseInt(obj, 10) === obj

  3. }

  4. isInteger(3) // true

  5. isInteger(3.3) // false

  6. isInteger('') // false

  7. isInteger('3') // false

  8. isInteger(true) // false

  9. isInteger([]) // false
复制代码

       很不错,但也有一个缺点

  1. isInteger(1000000000000000000000) // false
复制代码

       竟然返回了false,没天理啊。原因是parseInt在解析整数之前强迫将第一个参数解析成字符串。这种方法将数字转换成整型不是一个好的选择。

四、通过位运算判断

  1. function isInteger(obj) {

  2.     return (obj | 0) === obj

  3. }

  4. isInteger(3) // true

  5. isInteger(3.3) // false

  6. isInteger('') // false

  7. isInteger('3') // false

  8. isInteger(true) // false

  9. isInteger([]) // false
复制代码

       这个函数很不错,效率还很高。但有个缺陷,上文提到过,位运算只能处理32位以内的数字,对于超过32位的无能为力,如

  1. isInteger(Math.pow(2, 32)) // 32位以上的数字返回false了
复制代码

       当然,多数时候我们不会用到那么大的数字。

五、ES6提供了Number.isInteger

  1. Number.isInteger(3) // true

  2. Number.isInteger(3.1) // false

  3. Number.isInteger('') // false

  4. Number.isInteger('3') // false

  5. Number.isInteger(true) // false

  6. Number.isInteger([]) // false
复制代码

       目前,最新的Firefox和Chrome已经支持。
来源:http://www.cnblogs.com/snandy/p/3824828.html
0 0
原创粉丝点击