js数据类型检测的4种方法

1.typeof

缺点:对null和Array等类型的检测不是很方便

typeof null; //"object"
typeof []; //"object"

2.instanceof

缺点:1.只适用于对象类型

        2.只要当前的这个类在实例的原型链上,检测出来的结果都是true

123 instanceof Number; //false
null instanceof null; //TypeError
null instanceof Object; //false
function A(){}
function B(){}
A.prototype=new B();
var aObj=new A();
aObj instanceof B;//true
aObj instanceof A;//true

 3.constructor

注意:在类继承时会出错

function A(){};
function B(){};
A.prototype = new B();
var aObj = new A();
aObj.constructor === B; //true;
aObj.constructor === A; //false;

 4.自定义方法实现(比较通用)

function getType(o){
  return Object.prototype.toString.call(o).slice(8,-1);
}

 测试:

getType(null); //"Null"
getType(undefined); //"Undefined"
getType([]); //"Array"
getType({}); //"Object"
getType(()=>{}); //"Function"
getType(document.createElement('div')); //"HTMLDivElement"

 

猜你喜欢

转载自cobain-li.iteye.com/blog/2333451
今日推荐