JS中检测数据类型的多种方法

面试当中经常会问到检测 js 的数据类型,我在工作当中也会用到这些方法。让我们一起走起!!!

首先给大家上一个案例

1 console.log(typeof "langshen");       // String
2 console.log(typeof 666);              // Number
3 console.log(typeof true);             // Boolean
4 console.log(typeof false);            // Boolean
5 console.log(typeof function(){});     // Function
6 console.log(typeof undefined);        // Undefined
7 console.log(typeof null);             // Object
8 console.log(typeof []);               // Object
9 console.log(typeof {});               // Object

通过这些案例大家不难看出 

第一种 : 当 typeof 检测基本数据类型(Number、String、Boolean 、Undefined、Null)的时候是没有问题的。

但是检测引用型数据类型(Array、Object、RegExp等)的时候全都是 Object。

由于 typeof 检测的数据类型不是那么的 perfect !!!会有局限性。

使用场景:

      可以判断传递的参数是否有值

1 function fn(a, b) {
2   if (typeof b === "undefined") { // 没有传递参数
3     b = 0;
4   }
5   console.log(a, b); //1 0
6 }
7 fn(1);

第二种 : instanceof   检测一个实例是不是属于某个类

1 console.log("langshen" instanceof String);         //false
2 console.log(666 instanceof Number);                //false
3 console.log(true instanceof Boolean);              //false
4 console.log(null instanceof Null);
5 console.log(undefined instanceof Undefined);
6 console.log([] instanceof Array);                  //true
7 console.log(function(){} instanceof Function);     //true
8 console.log({} instanceof Object);                 //true

咱们先不要看 null 和 undefined

首先看基本数据类型,打印出来的都是false,这是为什么呢?

前三个都是以对象字面量创建的基本数据类型,但是却不是所属类的实例,只有实例方式创建出来的才是标准的对象数据类型值

如果我们换种方式来检测

1 new String("langshen") instanceof String       //true
2 new Number(666) instanceof Number              //true
3 new Boolean(true) instanceof Boolean           //true

当我们通过New的方式去创建基本数据类型就输出true

所以当我们检测的数据只要在当前实例的原型链上,我们用其检测出来的结果都是true 。

猜你喜欢

转载自www.cnblogs.com/langshening/p/10119418.html
今日推荐