數(shù)據(jù)類型判斷
-
typeof 操作符返回一個字符串,指示未經(jīng)計算的操作數(shù)的類型普泡。
<pre>
var a = 'abc'; console.log(typeof a);//string
var b = 1; console.log(typeof b); //number
var c = false; console.log(typeof c); //boolean
console.log(typeof undefined); //undefined
console.log(typeof null); //object
console.log(typeof {});// object
console.log(typeof []);//object
console.log(typeof (function(){}));//function
</pre>
數(shù)組類型判斷
-
instanceof,判斷一個變量是否某個對象的實例
<pre>
var arr = [];
arr instanceof Array;//true
</pre> -
constructor屬性返回對創(chuàng)建此對象的函數(shù)的引用今膊。
<pre>
var arr = [];
arr.constructor === Array; //true
</pre> -
Object.prototype.toString(),為了每個對象都能通過 Object.prototype.toString() 來檢測季二,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式來調(diào)用谷徙,把需要檢測的對象作為第一個參數(shù)傳入塘慕。
<pre>
var arr = [];
Object.prototype.toString.call(arr) === '[object Array]';//true
//其他類型判斷
Object.prototype.toString.call(123) === '[object Number]';
Object.prototype.toString.call('abc')) === '[object String]';
Object.prototype.toString.call(undefined) === '[object Undefined]';
Object.prototype.toString.call(true) === '[object Boolean]';
Object.prototype.toString.call(function(){}) === '[object Function]';
Object.prototype.toString.call(new RegExp()) === '[object RegExp]';
Object.prototype.toString.call(null) === '[object Null]';
</pre> -
Array.isArray() 確定傳遞的值是否為Array。
<pre>
var arr = [];
Array.isArray(arr);//true
</pre>