JavaScript测试数据类型的三种方法

typeof


console.log(typeof a);    //undefined

console.log(typeof(true));  //boolean

console.log(typeof '111');  //string

console.log(typeof 111);   //number

console.log(typeof NaN);   //number

console.log(typeof null);  //object


var str = new String();

console.log(typeof(str));    //object

 
var  fn = function(){};

console.log(typeof(fn));  //function

 
class Box{

  constructor(){

  }

}

var box = new Box();

console.log(typeof box);  //object

Object.prototype.toString.call();


console.log(Object.prototype.toString.call("aaa"));  //[object String]
 
console.log(Object.prototype.toString.call(111));  //[object Number]
 
console.log(Object.prototype.toString.call(true));  //[object Boolean]
 
console.log(Object.prototype.toString.call(undefined));  //[object Undefined]
 
console.log(Object.prototype.toString.call(null));  //[object Null]
 
console.log(Object.prototype.toString.call({name: "zhang"}));  //[object Object]
 
console.log(Object.prototype.toString.call(function(){}));  //[object Function]
 
console.log(Object.prototype.toString.call([]));  //[object Array]
 
console.log(Object.prototype.toString.call(new Date));  //[object Date]
 
console.log(Object.prototype.toString.call(/a/));  //[object RegExp]

class Test{
  constructor(){

  }
}
var test = new Test();
console.log(Object.prototype.toString.call(test));  //[object Object]

constructor


console.log((111).constructor.name)   //Number

console.log(("111").constructor.name)    //String

console.log((aaa).constructor.name)   //aaa is not defined

console.log((/a/).constructor.name)   //RegExp

console.log((true).constructor.name)   //Boolean

console.log(({name:"zhang"}).constructor.name)   //Object

console.log((new Date).constructor.name)   //Date

console.log(([]).constructor.name)   //Array

console.log((function(){}).constructor.name)   //Function

class Box{
  constructor(){

  }
}
var test = new Box();
console.log(test.constructor.name)   //Box
原文地址:https://www.cnblogs.com/JHJavaScript/p/11420770.html