数据类型与类型检测
<h4>问题:数据类型及其类型检测</h4>
<h4>思路:typeof 检测 基础数据类型</h4>
<hr />
<p><strong>js中的数据类型有6种:</strong></p>
<pre><code>基础数据类型5种:Boolean、String、Number、null、undefined
复杂数据类型:Object</code></pre>
<h5>如何对数据类型进行判断???</h5>
<pre><code>typeof true; //"boolean"
typeof "judy"; //"string"
typeof 10; //"number"
typeof undefined; //"undefined"
typeof null ; //'object'
typeof ({}) ; //"object"
注意:对于普通数据类型,只需用typeof来进行判断就可以
typeof里面的返回值里面,null和Object返回值都是Object,
而其余的都是对应的字符串。包含function
function a(){};
typeof a;//"function</code></pre>
<h5>一元运算符有很高的优先级,即使我们做多个 && || 的逻辑判断时,typeof依然可以连着写,而不需要使用()把每一个typeof包裹起来</h5>
<pre><code>typeof a ==='number' && typeof b === 'string'</code></pre>
<h5>问题:如何对Object类型进行判断?</h5>
<h5>思路: 其实对于Object的判断主要区分某个对象是否为数组</h5>
<h6>1.使用instanceof判断</h6>
<pre><code>console.log(a instanceof Array);//true 不建议使用</code></pre>
<h5>2.使用原型链上的constructor判断</h5>
<pre><code>console.log(a._proto_.constructor === Array) //true 不建议使用</code></pre>
<p>这两种方法,看上去不错,但是实际上还是有些漏洞的,当我们的页面中存在多个frame,并且我们的判断是在两个iframe之间的时候,就很有可能出现问题了。由于每个iframe都属于自己的window对象,跨frame实例化的对象彼此是不共享原型链的,因此导致上述检测代码失效</p>
<pre><code>var iframe = document.createElement('iframe'); //创建iframe
document.body.appendChild(iframe); //添加到body中
xArray = window.frames[window.frames.length-1].Array; //将xArray指向第二个iframe的引用
var arr = new xArray(1,2,3); // 声明数组[1,2,3]
alert(arr instanceof Array); // false
alert(arr.constructor === Array); // false </code></pre>
<h5>3.使用Array.isArray() 方法判断</h5>
<pre><code>var a = [];
console.log(Array.isArray(a)); //true</code></pre>
<h5>4.使用Object.prototype.toString.call()方法判断</h5>
<pre><code>var a = {};
var b = [];
function c () {}
console.log(Object.prototype.toString.call(a)); //'[object Object]'
console.log(Object.prototype.toString.call(b)); //'[object Array]'
console.log(Object.prototype.toString.call(c)); //"[object Function]"</code></pre>
<p><strong> Object.prototype.toString方法在ECMAScript 3中规范中就存在,也不存在兼容性问题。</strong></p>