typeof + instanceof+toString+constructor是如何判斷javascript數據類型的
來源:程序員人生 發布時間:2014-09-25 04:51:08 閱讀次數:3150次
一、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將會報錯(類似于空指針異常)。
測試:
function Foo(){}
Foo.prototype = new Aoo();//JavaScript 原型繼承
var foo = new Foo();
console.log(foo instanceof Foo)//true
console.log(foo instanceof Aoo)//true
console.log(Object instanceof Object);//true
console.log(Function instanceof Function);//true
console.log(Number instanceof Number);//false
console.log(String instanceof String);//false
console.log(Function instanceof Object);//true
console.log(Foo instanceof Function);//true
console.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): [object
Undefined]
{}.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繼承自B
var 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>); // true
console.log({}.constructor == <strong>Object</strong>); // true
console.log("string".constructor == <strong>String</strong>); // true
console.log((123).constructor == <strong>Number</strong>); // true
console.log(true.constructor == <strong>Boolean</strong>); // true
console.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;
},
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈