js类型检测

1. 基本数据类型(使用typeof)

  null,undefined,number,string,boolean

var n = null, u = undefined, num = 12, s = "123", b = true;

alert(typeof n);  //object

alert(typeof u);  //undefined

alert(typeof num);  //number

alert(typeof s);  //string

alert(typeof b);  //boolean

var o = new Object();

alert(typeof o);  //object

  typeof在检测基本数据类型时,非常有效,但是在检测引用类型时用处不大,所以有了instanceof。

2.引用数据类型(使用instanceof)

var o = new Object();

alert(o instanceof Object);  //true

var a = [1,2];

alert(a instanceof Array);  //true

var r = /123/;

alert(r instanceof RegExp);  //true

 instanceof Object  检测object类

 instanceof Array   检测数组

 instanceof RegExp 检测正则

综上:

  检测基本数据类型(null,undefined,number,string,boolean)使用typeof,

  检测引用数据类型(Object,Array,RegExp)使用instanceof

一直走下去,不容易
原文地址:https://www.cnblogs.com/lpy001/p/6247936.html