JS判斷數據類型方法(1)- Object.prototype.toString

1.Object.prototype.toString用來判斷類型再合適不過,借用它幾乎可以判斷所有類型的數據。

console.log(Object.prototype.toString.call({}))//[object Object]
console.log(Object.prototype.toString.call([]))//[object Array]
console.log(Object.prototype.toString.call(function(){}))//[object Function]
console.log(Object.prototype.toString.call(new Set()))//[object Set]
console.log(Object.prototype.toString.call(new Map()))//[object Map]
console.log(Object.prototype.toString.call(null))//[object Null]
console.log(Object.prototype.toString.call())//[object Undefined]

一個類型判斷函數:

function isType(data, type) {
    const typeObj = {
        '[object String]': 'string',
        '[object Number]': 'number',
        '[object Boolean]': 'boolean',
        '[object Null]': 'null',
        '[object Undefined]': 'undefined',
        '[object Object]': 'object',
        '[object Array]': 'array',
        '[object Function]': 'function',
        '[object Date]': 'date', // Object.prototype.toString.call(new Date())
        '[object RegExp]': 'regExp',
        '[object Map]': 'map',
        '[object Set]': 'set',
        '[object HTMLDivElement]': 'dom', // document.querySelector('#app')
        '[object WeakMap]': 'weakMap',
        '[object Window]': 'window',  // Object.prototype.toString.call(window)
        '[object Error]': 'error', // new Error('1')
        '[object Arguments]': 'arguments',
    }
    let name = Object.prototype.toString.call(data) // 借用Object.prototype.toString()獲取數據類型
    let typeName = typeObj[name] || '未知類型' // 匹配數據類型
    return typeName === type // 判斷該數據類型是否爲傳入的類型
}
console.log(
    isType({}, 'object'), // true
    isType([], 'array'), // true
    isType(new Date(), 'object'), // false
    isType(new Date(), 'date'), // true
)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章