通常情況下用typeof 判斷就可以了,遇到預知object型別的情況可以選用instanceof或constructor方法,實在沒轍就使用$.type()方法。
一、typeofalert(
typeof a) ------------>string
alert(
typeof b) ------------>number
alert(
typeof c) ------------>object
alert(
typeof d) ------------>object
alert(
typeof e) ------------> function
alert(
typeof f) ------------> function
typeof無法判斷null,因為null的機器碼均為0,so用typeof判斷null直接當做物件看待
alert(typeofnull) ------------> object
二、判斷已知物件型別的方法: instanceofalert(c
instanceof array) ---------------> true
alert(d
instanceof date) ---------------->true
new data('2021/11/23') instanceof data --->true
alert(f
instanceof function) ------------> true
alert(f
instanceof
function) ------------> false
注:instanceof 後面一定要是物件型別,並且大小寫不能錯,
原理就是只要右邊變數的prototype在左邊變數的原型鏈即可。
三、根據物件的constructor判斷: constructoralert(c.constructor === array) ----------> true
alert(d.constructor === date) -----------> true
alert(e.constructor === function) -------> true
四、通用的object.prototype.tostringalert(object.prototype.tostring.call(a) === 『[object string]') -------> true;
alert(object.prototype.tostring.call(b) === 『[object number]') -------> true
;alert(object.prototype.tostring.call(c) === 『[object array]') -------> true;
alert(object.prototype.tostring.call(d) === 『[object date]') -------> true
;alert(object.prototype.tostring.call(e) === 『[object function]') -------> true;
alert(object.prototype.tostring.call(f) === 『[object function]') -------> true;
五、萬能之王jquery.type()---->簡寫$.type()jquery.type(
true ) === "boolean"jquery.type( 3 ) === "number"jquery.type( "test" ) === "string"jquery.type(
function(){} ) === "function"jquery.type( ) === "array"jquery.type(
new date() ) === "date"jquery.type(
new error() ) === "error" //
as of jquery 1.9
jquery.type( /test/ ) === "regexp"
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 判斷...