美文网首页
判断输入是否为整数

判断输入是否为整数

作者: zhangwinwin | 来源:发表于2019-03-14 11:23 被阅读0次

    1、使用typeof和取余运算符%判断

    const isInteger = obj => {
        return typeof obj === 'number' && obj % 1 === 0
    }
    

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

    const isInteger = obj => {
        return Math.round(obj) === obj
    }
    

    3、使用ES6中的Number.isInteger

    const isInteger = obj => {
        return Number.isInteger(obj)
    }
    

    4、使用parseInt判断

    const isInteger = obj => {
        return parseInt(obj) === obj
    }
    

    5、使用使用位运算

    const isInteger = obj => {
        return (obj | 0) === obj
        // 只能处理32位以内的数字
    }
    

    相关文章

      网友评论

          本文标题:判断输入是否为整数

          本文链接:https://www.haomeiwen.com/subject/vkhqmqtx.html