美文网首页
js判断类型的方法

js判断类型的方法

作者: 祈求者 | 来源:发表于2018-03-17 23:46 被阅读9次

js判断类型的几种方法

1.typeof

typeof只能判断区分基本类型,即number、string、boolean、undefinded和object这5种

2. 使用constructor 通过判断对象的构造函数来判断对象类型

var arr = [];
console.log(arr.constructor) // Array

3.instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。

var arr =[] ;
console.log(arr instanceof Array) // true

4.Object.prototype.toString方法,判断对象属于那种内置对象类型

要精确判断对象类型可以使用这种方法

var arr = [];
console.log(Object.prototype.toString.call(arr))    // [object Array]
  

举个例子

比如在iframe中,只有第四种方法才能的判断出类型。


  window.onload = function(){
                var oF = document.createElement('iframe');
                document.body.appendChild(oF);

                var ifArray = window.frames[0].Array;
                var arr = new ifArray();
                alert(arr.constructor == Array); // false
                alert(arr instanceof Array); // false
                alert(Object.prototype.toString.call(arr) =='[object Array]' ); // true
}

相关文章

网友评论

      本文标题:js判断类型的方法

      本文链接:https://www.haomeiwen.com/subject/gepsqftx.html