js数据类型检测工具

1. typeof:

 1 // typeof: js检测基本数据类型的最佳工具(除了null以外), 还可以检测引用类型function。
 2 // eg:
 3 console.log(typeof a); //'undefined'
 4 
 5 console.log(typeof (true)); //'boolean'
 6 
 7 console.log(typeof '123'); //'string'
 8 
 9 console.log(typeof 123); //'number'
10 
11 console.log(typeof NaN); //'number'
12 
13 console.log(typeof Symbol('hello')); //'symbol' 
14 
15 let fn = function(){};
16 console.log(typeof fn); //"function"

 

2. instanceof:

 1 // instanceof:用来鉴别当前引用类型是否是某个给定引用类型(构造函数)的实例(注:这个构造函数除了Object以外,
 2 // 因为所有的引用类型的值都是Object的实例),如果是的话返回true;
 3 // eg:
 4 var obj = function(){};
 5 obj instanceof Function; //true
 6 obj = [];
 7 obj instanceof Array; //true
 8 obj = new Date()
 9 obj instanceof Date; //true
10 obj = /w/g;
11 obj instanceof RegExp; //true
12 obj = {};
13 obj instanceof Object; //true
14 // 以上这些都属于Object的实例

3. Object.prototype.toString.call(obj):

 1 // Object.prototype.toString.call(obj):类型检测界的扛把子,可以精准判断所传入参数的数据类型。
 2 // eg:
 3 console.log(Object.prototype.toString.call("jerry"));//[object String]
 4 console.log(Object.prototype.toString.call(12));//[object Number]
 5 console.log(Object.prototype.toString.call(true));//[object Boolean]
 6 console.log(Object.prototype.toString.call(undefined));//[object Undefined]
 7 console.log(Object.prototype.toString.call(null));//[object Null]
 8 console.log(Object.prototype.toString.call({name: "jerry"}));//[object Object]
 9 console.log(Object.prototype.toString.call(function(){}));//[object Function]
10 console.log(Object.prototype.toString.call([]));//[object Array]
11 console.log(Object.prototype.toString.call(new Date));//[object Date]
12 console.log(Object.prototype.toString.call(/\d/));//[object RegExp]
13 console.log(Object.prototype.toString.call(Symbol()));//[object Symbol]
14 function Person(){};
15 console.log(Object.prototype.toString.call(new Person));//[object Object]

 

 

posted @ 2021-10-26 18:40  CooperGao  阅读(203)  评论(0)    收藏  举报