js判斷資料型別

2022-10-08 23:42:22 字數 2093 閱讀 2468

返回資料型別,包含這7種: number、boolean、symbol、string、object、undefined、function。

typeof null   返回型別錯誤,返回object

引用型別,除了function返回function型別外,其他均返回object。

其中,null 有屬於自己的資料型別 null , 引用型別中的 陣列、日期、正則 也都有屬於自己的具體型別,而 typeof 對於這些型別的處理,只返回了處於其原型鏈最頂端的 object 型別,沒有錯,但不是我們想要的結果。

tostring() 是 object 的原型方法,呼叫該方法,預設返回當前物件的 [[class]] 。這是乙個內部屬性,其格式為 [object ***] ,其中 *** 就是物件的型別。

判斷型別舉例:

object.prototype.tostring.call('') ;   // [object string]

object.prototype.tostring.call(1) ; // [object number]

object.prototype.tostring.call(true) ; // [object boolean]

object.prototype.tostring.call(symbol()); //[object symbol]

object.prototype.tostring.call(undefined) ; // [object undefined]

object.prototype.tostring.call(null) ; // [object null]

object.prototype.tostring.call(new function()) ; // [object function]

object.prototype.tostring.call(new date()) ; // [object date]

object.prototype.tostring.call() ; // [object array]

object.prototype.tostring.call(new regexp()) ; // [object regexp]

object.prototype.tostring.call(new error()) ; // [object error]

object.prototype.tostring.call(document) ; // [object htmldocument]

object.prototype.tostring.call(window) ; //[object global] window 是全域性物件 global 的引用

constructor是原型prototype的乙個屬性,當函式被定義時候,js引擎會為函式新增原型prototype,並且這個prototype中constructor屬性指向函式引用, 因此重寫prototype會丟失原來的constructor。

不過這種方法有問題:

1:null 和 undefined 無constructor,這種方法判斷不了。

2:還有,如果自定義物件,開發者重寫prototype之後,原有的constructor會丟失,因此,為了規範開發,在重寫物件原型時一般都需要重新給 constructor 賦值,以保證物件例項的型別不被篡改。

instanceof 是用來判斷 a 是否為 b 的例項,表示式為:a instanceof b,如果 a 是 b 的例項,則返回 true,否則返回 false。 在這裡需要特別注意的是:instanceof 檢測的是原型

由上圖可以看出的原型指向array.prototype,間接指向object.prototype, 因此 instanceof array 返回true, instanceof object 也返回true。

instanceof 只能用來判斷兩個物件是否屬於例項關係, 而不能判斷乙個物件例項具體屬於哪種型別。

js判斷資料型別

1 typeof 形如 var x xx typeof x string 返回型別有 undefined string number boolean function object 缺點 對於object型別不能細分是什麼型別 優點 對空null的判斷 undefined 的應用 2 instanc...

js判斷資料型別

了解js的都知道,有個typeof 用來判斷各種資料型別,有兩種寫法 typeof typeof 如下例項 typeof 2 輸出 number typeof null 輸出 object typeof 輸出 object typeof 輸出 object typeof function 輸出 fu...

js判斷資料型別

1 判斷是否為陣列型別 2 判斷是否為字串型別 3 判斷是否為數值型別 isnan 變數 如果為true就是數字型別 注意這個函式一般針對數字型別來判斷是否值為nan,若變數為非數字型別,則先轉化為數字型別再做判斷,用此函式時,別忘考慮空串和空格 這倆轉化為數字是0 4 判斷是否為日期型別 5 判斷...