JavaScript数据类型检测
1. typeof
typeof会把数组、对象、null都判断为object,其他正确。
console.log(typeof 2); //number console.log(typeof true); //boolean console.log(typeof 'str'); //string console.log(typeof []); //object console.log(typeof function(){}); //function console.log(typeof {}); //object console.log(typeof undefined); //undefined console.log(typeof null); //object
instanceof
instanceof可以正确判断对象的类型,其内部运行机制是判断在其原型链中能否找到该类型的原型。
instanceof只能用于判断引用类型,而不能判断基本类型。
console.log(2 instanceof Number); //false console.log(true instanceof Boolean); //false console.log('str' instanceof String); //false console.log([] instanceof Array); //true console.log(function(){} instanceof Function); //true console.log({} instanceof Object); //true
constructor
constructor不仅可以判断数据类型,还能让对象实例通过constructor对象访问它的构造函数。
但是如果使用了另一个对象改变当前对象的原型,constructor就不能用来判断当前对象的数据类型了。
console.log((2).constructor === Number); //true console.log((true).constructor === Boolean); //true console.log(('str').constructor === String); //true console.log(([]).constructor === Array); //true console.log((function(){}).constructor === Function); //true console.log(({}).constructor === Object); //true
Object.prototype.toString.call()
最准确的判断方式,使用Object对象的原型方法toString来判断数据类型
let a = Object.prototype.toString; console.log(a.call(2)); //[object Number] console.log(a.call(true)); //[object Boolean] console.log(a.call('str')); //[object String] console.log(a.call([])); //[object Array] console.log(a.call(function(){})); //[object Function] console.log(a.call({})); //[object Object] console.log(a.call(undefined)); //[object Undefined] console.log(a.call(null)); //[object Null]
本文作者:zwx1123
本文链接:https://www.cnblogs.com/zwx1123/p/17606508.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步