JavaScript基礎----類型判斷typeof()、Object.prototype.toString.call()

 

typeof()

Object.prototype.toString.call()

用法 typeof(val) Object.prototype.toString.call(val)
數字 number [object Number]
字符串 string [object String]
undefined undefined [object Undefined]
function function [object Function]
布爾值 boolean [object Boolean]
null object [object Null]
對象 object [object Object]
數組 object [object Array]
日期 object [object Date]
正則 object [object RegExp]
JSON object [object JSON]
Math object [object Math]
Error object [object Error]

從表格裏可以看出,typeof可以判斷出5種類型(注意:null返回的是object),Object.prototype.toSting.call()可以判斷出13種類型。

let number = 1,              // Number       number
    string = '123',          // String       string
    boolean = true,          // Boolean      boolean
    und = undefined,         // Undefined    undefined
    func = function a(){},   // Function     function
    nul = null,              // Null         object
    obj = {a: 1},            // Object       object
    array = [1, 2, 3],       // Array        object
    date = new Date(),       // Date         object
    error = new Error(),     // Error        object
    reg = /a/g,              // RegExp       object
    json = JSON,             // JSON         object
    math = Math;             // Math         object

function checkType() {
    for (let i = 0, _i = arguments.length, arg = arguments; i < _i; i++) {
        console.log(Object.prototype.toString.call(arg[i]).slice(8, -1), typeof (arg[i]));
    }
}

checkType(number, string, boolean, und, func, nul, obj, array, date, error, reg, json, math)

原文出處:https://github.com/mqyqingfeng/Blog/issues/28

 

 

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