1.typeof 能判斷出字符串、數(shù)字、方法和undefined,array、null、object判斷不出
let num = 1;
let str = "x";
let fn = function user(){}
let arr = [1,2]
let obj = {name:"zhangs"}
let und;
let nul = null;
console.log(typeof num) //number
console.log(typeof str) //string
console.log(typeof fn)//function
console.log(typeof und) //undefined
console.log(typeof arr) //object
console.log(typeof obj) //object
console.log(typeof nul) //object
- instanceof 如 a instanceof b, 判斷a的原型鏈上是否有b的原型
let fn = function user(){}
let arr = [1,2]
let obj = {name:"zhangs"}
let und;
console.log(fn instanceof Function) //true
console.log(arr instanceof Array) //true
console.log(arr instanceof Object) //true
console.log(obj instanceof Object) //true
-
Object.getPrototypeOf() 返回參數(shù)的隱式原型 ,感覺有些雞肋
Object.getPrototypeOf ([]) === Array.prototype //true -
Object.prototype.toString.call()
這里解釋一下為什么Object.prototype.toString 可以調(diào)用call方法,首先我們知道call方法來源,它來自Function.prototype,
這是因為Object.prototype.toString 本身是一個方法,是方法它的原型鏈上就會出現(xiàn)Function的原型對象,所有就有了call方法,這跟一個對象如let obj= {},obj可以使用toString一個意思,因為toString在Object.prototype上。文章來源:http://www.zghlxwxcb.cn/news/detail-703846.html
let num = 1;
let str = "x";
let fn = function user(){}
let arr = [1,2]
let obj = {name:"zhangs"}
let und;
let nul = null;
console.log(Object.prototype.toString.call(obj)); //[object Object]
console.log(Object.prototype.toString.call(fn)); //[object Function]
console.log(Object.prototype.toString.call(arr)); //[object Array]
console.log(Object.prototype.toString.call(nul)); //[object Null]
console.log(Object.prototype.toString.call(und)); //[object Undefined]
console.log(Object.prototype.toString.call(num)); //[object Number]
console.log(Object.prototype.toString.call(str)); //[object String]
這種方式還是挺萬能的,沒看出來有什么局限性文章來源地址http://www.zghlxwxcb.cn/news/detail-703846.html
到了這里,關(guān)于日常開發(fā)小匯總(3)js類型判斷的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!