判断js中的数据类型的方法
生活随笔
收集整理的這篇文章主要介紹了
判断js中的数据类型的方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在 判斷js中的數據類型 我們通常會使用typeOf()方法,
? ? ? ?typeof?? 2? ? ? ? ?輸出?? number
? ? ? typeof?? null? ? ? ?輸出???object
? ?? ? typeof?? {}? ? ? 輸出???object
? ? ? ?typeof??? []???? 輸出???object
? ? ? ?typeof?? (function(){}) 輸出??function
? ? ? ?typeof??? undefined? 輸出??undefined
? ? ? ?typeof?? '222'? ? ? 輸出? ? string
????? typeof? true? ? ? ??輸出? ? ?boolean
typeof? 用來判斷null ,對象 , 數組 都會返回 object,那我們怎么來區分他們呢?
下面就用到了
判斷已知對象類型的方法: instanceof
var a = "iamstring.";
var b = 222;
var c= [1,2,3];
var d = new Date();
var e = function(){alert(111);};
var f = function(){this.name="22";};
alert(c instanceof Array) ---------------> true alert(d instanceof Date) alert(f instanceof Function) ------------> true alert(f instanceof function) ------------> false 注意:instanceof 后面一定要是對象類型,并且大小寫不能錯,該方法適合一些條件選擇或分支。
?
?
?
?
?
無敵萬能的方法:jquery.type()
如果對象是undefined或null,則返回相應的“undefined”或“null”。 jQuery.type( undefined ) === "undefined" jQuery.type() === "undefined" jQuery.type( window.notDefined ) === "undefined" jQuery.type( null ) === "null" 如果對象有一個內部的[[Class]]和一個瀏覽器的內置對象的 [[Class]] 相同,我們返回相應的 [[Class]] 名字。 (有關此技術的更多細節。 ) 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" 其他一切都將返回它的類型“object”。?
??
轉載于:https://www.cnblogs.com/ysdemo/p/9782542.html
總結
以上是生活随笔為你收集整理的判断js中的数据类型的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue组件通信v兄弟组件通信eventb
- 下一篇: Java并发编程(五):Java线程安全