JavaScript查看数据类型的方法

JS的数据类型

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

JavaScript查看数据类型的方法

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

一、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

二、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

Guess you like

Origin blog.csdn.net/qq_40829962/article/details/128238170