typeof + instanceof+toString+constructor是如何判斷javascript資料類型的,typeofinstanceof
一、typeof
JS中的變數是鬆散類型(即弱類型)的,可以用來儲存任何類型的資料。
typeof 可以用來檢測給定變數的資料類型,可能的返回值:
1. 'undefined' --- 這個值未定義;
2. 'boolean' --- 這個值是布爾值;
3. 'string' --- 這個值是字串;
4. 'number' --- 這個值是數值;
5. 'object' --- 這個值是對象或null;
6. 'function' --- 這個值是函數。
測試:
document.write("typeof(1): " + typeof(1) + "<br>");document.write("typeof(NaN): " + typeof(NaN) + "<br>");document.write("typeof(Number.MIN_VALUE): " + typeof(Number.MIN_VALUE) + "<br>")document.write("typeof(Infinity): " + typeof(Infinity) + "<br>")document.write("typeof(\"123\"): " + typeof("123") + "<br>")document.write("typeof(true): " + typeof(true) + "<br>")document.write("typeof(window): " + typeof(window) + "<br>")document.write("typeof(document): " + typeof(document) + "<br>")document.write("typeof(null): " + typeof(null) + "<br>")document.write("typeof(eval): " + typeof(eval) + "<br>")document.write("typeof(Date): " + typeof(Date) + "<br>")document.write("typeof(sss): " + typeof(sss) + "<br>")document.write("typeof(undefined): " + typeof(undefined) + "<br>")測試結果:
typeof(1): number
typeof(NaN): number
typeof(Number.MIN_VALUE): number
typeof(Infinity): number
typeof("123"): string
typeof(true): boolean
typeof(window): object
typeof(document): object
typeof(null): object
typeof(eval): function
typeof(Date): function
typeof(sss): undefined
typeof(undefined): undefined
參考資料
http://javaeyetodj.iteye.com/blog/1199125
http://www.cnblogs.com/lidabo/archive/2011/12/29/2305770.html
二、instanceof
在 JavaScript 中,判斷一個變數的類型常常會用 typeof 運算子,在使用 typeof 運算子時採用參考型別儲存值會出現一個問題,無論引用的是什麼類型的對象,它都返回 “object”。這就需要用到instanceof來檢測某個對象是不是另一個對象的執行個體。
通常來講,使用
instanceof 就是判斷一個執行個體是否屬於某種類型。
另外,更重的一點是 instanceof 可以在繼承關係中用來判斷一個執行個體是否屬於它的父類型。上面的代碼中是判斷了一層繼承關係中的父類,在多層繼承關係中,instanceof 運算子同樣適用。
instanceof 檢測一個對象A是不是另一個對象B的執行個體的原理是:查看對象B的prototype指向的對象是否在對象A的[[prototype]]鏈上。如果在,則返回true,如果不在則返回false。不過有一個特殊的情況,當對象B的prototype為null將會報錯(類似於null 指標異常)。
測試:
function Foo(){}Foo.prototype = new Aoo();//JavaScript 原型繼承var foo = new Foo();console.log(foo instanceof Foo)//trueconsole.log(foo instanceof Aoo)//trueconsole.log(Object instanceof Object);//trueconsole.log(Function instanceof Function);//trueconsole.log(Number instanceof Number);//falseconsole.log(String instanceof String);//falseconsole.log(Function instanceof Object);//trueconsole.log(Foo instanceof Function);//trueconsole.log(Foo instanceof Foo);//false參考資料
http://www.studyofnet.com/news/175.html
三、toString
Object.prototype.toString().call(param) 返回param的類型(string,格式是[object class]) 。
toString() 方法可把一個邏輯值轉換為字串,並返回結果,文法為:booleanObject.toString()。剛才我說了,js中的對象都是繼承的Object,這些對象都自訂的有函數或者重構了Object的部分函數,而且它們都對toString()函數進行了重寫。所以我們不能像1中直接寫param.prototype.toString()這樣就執行的是param自己重寫後的toString()函數了。
在toString方法被調用時,會執行下面的操作步驟:
1. 擷取this對象的[[Class]]屬性的值.
2. 計算出三個字串"[object ", 第一步的操作結果Result(1), 以及 "]"串連後的新字串.
3. 返回第二步的操作結果Result(2).
在ES3中,規範文檔並沒有總結出[[class]]內部屬性一共有幾種,不過我們可以自己統計一下,原生對象的[[class]]內部屬性的值一共有10種.分別是:"Array", "Boolean", "Date", "Error", "Function", "Math", "Number", "Object","RegExp", "String".所以Object.prototype.toString()的輸出結果就是這種格式的字串[object Array],[object Boolean]。
所以說toString可以判斷:
"Array", "Boolean", "Date", "Error", "Function", "Math", "Number", "Object","RegExp", "String"以上十種資料類型。
【
在ES5.1中,除了規範寫的更詳細一些以外,Object.prototype.toString方法和[[class]]內部屬性的定義上也有一些變化,Object.prototype.toString方法的規範如下:
在toString方法被調用時,會執行下面的操作步驟:
1 如果this的值為undefined,則返回"[object Undefined]".
2 如果this的值為null,則返回"[object Null]".
3 讓O成為調用ToObject(this)的結果.
4 讓class成為O的內部屬性[[Class]]的值.
5 返回三個字串"[object ", class, 以及 "]"串連後的新字串.
可以看出,比ES3多了1,2,3步.第1,2步屬於新規則,比較特殊,因為"Undefined"和"Null"並不屬於[[class]]屬性的值。經統計,可返回的類型有"Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp", "String"比ES3多了2種分別是arguments對象的[[class]]成了"Arguments",而不是以前的"Object",還有就是多個了全域對象JSON,它的[[class]]值為"JSON"。
】
最後的最後提醒大家,Object.prototype.toString().call(param)返回的[object class]中class首字母是大寫,像JSON這種甚至都是大寫,所以,大家判斷的時候可以都轉換成小寫,以防出錯,Object.prototype.toString().call(param).toLowerCase()即可。
測試:
document.write("{}.toString.call(1): " + {}.toString.call(1) + "<br>");document.write("{}.toString.call(NaN): " + {}.toString.call(NaN) + "<br>");document.write("{}.toString.call(Number.MIN_VALUE): " + {}.toString.call(Number.MIN_VALUE) + "<br>")document.write("{}.toString.call(Infinity): " + {}.toString.call(Infinity) + "<br>")document.write("{}.toString.call(\"123\"): " + {}.toString.call("123") + "<br>")document.write("{}.toString.call(true): " + {}.toString.call(true) + "<br>")document.write("{}.toString.call(window): " + {}.toString.call(window) + "<br>")document.write("{}.toString.call(document): " + {}.toString.call(document) + "<br>")document.write("{}.toString.call(null): " + {}.toString.call(null) + "<br>")document.write("{}.toString.call(eval): " + {}.toString.call(eval) + "<br>")document.write("{}.toString.call(Date): " + {}.toString.call(Date) + "<br>")document.write("{}.toString.call(undefined): " + {}.toString.call(undefined) + "<br>")document.write("{}.toString.call({}): " + {}.toString.call({}) + "<br>")document.write("{}.toString.call(sss): " + {}.toString.call(sss) + "<br>")
測試結果:
{}.toString.call(1): [object Number]
{}.toString.call(NaN): [object Number]
{}.toString.call(Number.MIN_VALUE): [object Number]
{}.toString.call(Infinity): [object Number]
{}.toString.call("123"): [object String]
{}.toString.call(true): [object Boolean]
{}.toString.call(window): [object global]
{}.toString.call(document): [object HTMLDocument]
{}.toString.call(null): [object Null]
{}.toString.call(eval): [object Function]
{}.toString.call(Date): [object Function]
{}.toString.call(undefined): [objectUndefined]
{}.toString.call({}): [object Object]
參考資料:
http://www.jb51.net/article/42864.htm
四、constructor
在W3C定義中的定義:constructor 屬性返回對建立此對象的數組函數的引用。
就是返回對象相對應的建構函式。從定義上來說跟instanceof不太一致,但效果都是一樣的
注意: constructor 在類繼承時會出錯
例如:
function A(){};function B(){};A.prototype = new B(); //A繼承自Bvar aObj = new A();alert(aobj.constructor === B)// -----------> true;alert(aobj.constructor === A) //-----------> false;而instanceof方法不會出現該問題,對象直接繼承和間接繼承的都會報true:
alert(aobj instanceof B) //----------------> true;alert(aobj instanceof B) //----------------> true;
言歸正傳,解決construtor的問題通常是讓對象的constructor手動指向自己:
aobj.constructor = A; //將自己的類賦值給對象的constructor屬性alert(aobj.constructor === A) //-----------> true;alert(aobj.constructor === B) //-----------> false; //基類不會報true了;
測試:
console.log([].constructor == <strong>Array</strong>); // trueconsole.log({}.constructor == <strong>Object</strong>); // trueconsole.log("string".constructor == <strong>String</strong>); // trueconsole.log((123).constructor == <strong>Number</strong>); // trueconsole.log(true.constructor == <strong>Boolean</strong>); // trueconsole.log((new Date()).constructor == <strong>Date</strong>);//true
參考資料:http://blog.sina.com.cn/s/blog_51048da70101grz6.html
五、jQuery中的類型判斷
type()方法
type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj;},
javascript instanceof 的問題
str='123';
str就是字串類型。
但是它並不是對象。
既然不是對象,你instanceof 任何東西都不可能是true
除非你這樣聲明
var str = new String('123')
javascript也會有自動拆裝箱的操作。
str = ‘123’
此時str是基礎資料型別 (Elementary Data Type)
但當你調用str.substring方法時。
javascript解譯器會將str臨時封裝成一個String對象,然後釋放掉。
所以str不是對象,但有時候也是對象。給你造成了困惑。
JavaScript中instanceof運算子的用法
instanceof則為判斷一個對象是否為某一資料類型,或一個變數是否為一個對象的執行個體;返回boolean類型
文法為 o instanceof A
以下為綜合執行個體:
1 <script type="text/javascript">
2 <!–
3 alert("typeof(1):" + typeof(1));//number
4 alert("typeof(\"abc\"):" + typeof("abc"));//string
5 alert("typeof(true):" +typeof(true));//boolean
6 alert("typeof(2009-2-4):" + typeof(2009-2-4));//number
7 alert("typeof(\"2009-2-4\"):" + typeof("2009-2-4"));//string
8 alert("typeof(m):" + typeof(m));//undefined
9 var d=new Date();
10 alert("typeof(d):" + typeof(d));//object
11 function Person(){};
12 alert("typeof(Person):" + typeof(Person));//function
13 var a=new Array();
14 alert("typeof(a):" + typeof(a));//object
15 alert("a instanceof Array:" + (a instanceof Array));
16 var h=new Person();
17 var o={};
18 alert("h instanceof Person:" + (h instanceof Person));//true
19 alert("h instanceof Object:" + (h instanceof Object));//true
20 alert("o instanceof Object:" + (o instanceof Object));//true
21 alert(typeof(h));//object
22 //–>
23 </script>