该文章概括一下常用的查看数据类型的方法

JS的数据类型
基本数据类型:String、Number、Null、Undefined、Boolean
引用数据类型:Object、Array、Function

typeof 变量

console.log(typeof 1);//number
console.log(typeof "HELLO WORLD");//string
console.log(typeof null);//object
console.log(typeof undefined);//undefined
console.log(typeof true);//Boolean
console.log(typeof false);//Boolean
console.log(typeof {name:"xiaoming"});//object
console.log(typeof function(){});//function
console.log(typeof [1,2,3,"a"]);//object

Object.prototype.toString.call(变量)

console.log(Object.prototype.toString.call(1));//[object Number]
console.log(Object.prototype.toString.call("HELLO WORLD"));//[object String]
console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call(false));//[object Boolean]
console.log(Object.prototype.toString.call({name:"xiaoming"}));[object Object]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call([1,2,3,"a"]));//[object Array]

变量.constructor

let a=1;
let b="HELLO WORLD";
let c=null;
let d=undefined;
let e=true;
let f=false;
let g={name:"xiaoming"};
let h=function(){};
let i=[1,2,3,"a"];
console.log(a.constructor.name);//Number
console.log(b.constructor.name);//String
//console.log(c.constructor.name);//报错:'constructor' of null
//console.log(d.constructor.name);//报错:'constructor' of undefined
console.log(e.constructor.name);//Boolean
console.log(f.constructor.name);//Boolean
console.log(g.constructor.name);//Object
console.log(h.constructor.name);//Function
console.log(i.constructor.name);//Array

总结

使用typeof方式查看数据类型时,null数组是object类型。
Object.prototype.toString.call()的方式最为详细。
constructor.name的方式无法查看nullundefined.

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐