JS判断字符串,布尔,数组,函数,对象,数字的类型

JS基本类型有数字、布尔、字符串和对象类型。

console.log(typeof(""))  // "string"
console.log(typeof(1))  // "number"
console.log(typeof(true))  // "boolean"
console.log(typeof(/^$/))  // "object"
console.log(typeof(Date))  // "function"
console.log(typeof(new Date()))  // "object"
console.log(typeof({
    
    }))  // "object"
console.log(typeof([]))  // "object"

由typeof检查可知:数组,对象,函数这几个返回的是 “object”
但是当想知道数组,对象,函数的类型时该怎么判断呢?
如下所示:

console.log(Object.prototype.toString.call(true))   //"[object Boolean]"
console.log(Object.prototype.toString.call(1))   //"[object Number]"
console.log(Object.prototype.toString.call(""))   //"[object String]"
console.log(Object.prototype.toString.call(function(){
    
    }))  //"[object Function]"
console.log(Object.prototype.toString.call([]))   //"[object Array]"
console.log(Object.prototype.toString.call({
    
    }))   //"[object Object]"
console.log(Object.prototype.toString.call(new Date()))   //"[object Date]"
console.log(Object.prototype.toString.call(/^$/))   //"[object RegExp]"

猜你喜欢

转载自blog.csdn.net/qq_37148353/article/details/119701504
今日推荐