判断输入是否为整数

2019-03-14  本文已影响0人  zhangwinwin

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位以内的数字
}
上一篇下一篇

猜你喜欢

热点阅读