數據類型判斷
-
typeof 操作符返回一個字符串,指示未經計算的操作數的類型。
<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>
數組類型判斷
-
instanceof,判斷一個變量是否某個對象的實例
<pre>
var arr = [];
arr instanceof Array;//true
</pre> -
constructor屬性返回對創建此對象的函數的引用。
<pre>
var arr = [];
arr.constructor === Array; //true
</pre> -
Object.prototype.toString(),為了每個對象都能通過 Object.prototype.toString() 來檢測,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式來調用,把需要檢測的對象作為第一個參數傳入。
<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>