js判斷數字、整數、字符串、布爾,特殊方法


 

整數:

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

整數:

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了
//當然,多數時候我們不會用到那么大的數字。

原:http://www.cnblogs.com/snandy/p/3824828.html

數字:

function isNumber(obj) {
    return obj === +obj
}

 

數字(es6):

Number.isInteger(3) // true

 

字符串和布爾:

// 判斷字符串
function isString(obj) {
    return obj === obj+''
}
// 判斷布爾類型
function isBoolean(obj) {
    return obj === !!obj
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM