Maison> interface Web> js tutoriel> le corps du texte

javascript怎么判断是否为整数

青灯夜游
Libérer: 2023-01-03 09:31:52
original
3462 Les gens l'ont consulté

方法:1、使用取余运算符来判断;2、使用“Math.round”、“Math.ceil”、“Math.floor”方法来来判断;3、使用parseInt函数来判断;4、通过位运算来判断;5、使用“Number.isInteger”来判断。

javascript怎么判断是否为整数

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

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

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

function isInteger(obj) { return obj%1 === 0 } isInteger(3) // true isInteger(3.3) // false  isInteger('') // true isInteger('3') // true isInteger(true) // true isInteger([]) // true
Copier après la connexion

对于空字符串、字符串类型数字、布尔true、空数组都返回了true。对这些类型的内部转换细节感兴趣的请参考:JavaScript中奇葩的假值
因此,需要先判断下对象是否是数字,比如加一个typeof

function isInteger(obj) { return typeof obj === 'number' && obj%1 === 0 } isInteger('') // false isInteger('3') // false isInteger(true) // false isInteger([]) // false
Copier après la connexion

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

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

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
Copier après la connexion

【推荐学习:js基础教程

方式三、通过parseInt判断

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、 //很不错,但也有一个缺点 isInteger(1000000000000000000000) // false
Copier après la connexion

原因是parseInt在解析整数之前强迫将第一个参数解析成字符串。这种方法将数字转换成整型不是一个好的选择。

方式四、通过位运算判断

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了
Copier après la connexion

方式五、ES6提供了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
Copier après la connexion

更多编程相关知识,请访问:编程视频!!

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!