扩展typeof来判断js变量的类型
生活随笔
收集整理的這篇文章主要介紹了
扩展typeof来判断js变量的类型
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Javascript 的 typeof可以獲取變量的類型,有如下6種返回值:?
1)number;?
2)string;?
3)boolean;?
4)object?
5)function;?
6)undefined.?
javascript判斷變量類型的自定義函數?
通常用typeof來判斷js變量的類型,但很多時候僅僅typeof滿足不了要求的。?
我寫了一個自定義函數來做這個事,判斷的比較全面了, 存為typeof_extend.js。
function varType(v){ if(typeof v==="object"){ if(v===null)return 'null'; if(v.constructor) return (v.constructor.toString()).match(/(?: )[\w\$]+/)[0]; if(typeof typeof2==='undefined' && window.execScript){ window.execScript('Function vbsTypeName(o):vbsTypeName=TypeName(o):End Function','vbscript'); window.execScript('function typeof2(o){return vbsTypeName(o)}','jscript'); } if(typeof typeof2!=='undefined'){ return typeof2(v); } return "object"; } return typeof v;
} //對于普通js常量和js對象,各瀏覽器是基本一致的
console.log(varType()); //undefined
console.log(varType(100)); //number
console.log(varType({})); //Object
console.log(varType([])); //Array
console.log(varType(/ /)); //RegExp
console.log(varType(new Date())); //Date
console.log(varType(Date)); //function
console.log(varType(Object)); //function
console.log(varType(RegExp)); //function //對于DOM對象,各瀏覽器可能會有不同值
console.log(varType(window)); //IE:HTMLWindow2 FF:Window
console.log(varType(document)); //IE:HTMLDocument FF:HTMLDocument
console.log(varType(document.body)); //IE:HTMLBody FF:HTMLBodyElement
console.log(varType(Option)); //IE:Object FF:function
console.log(varType(Image)); //IE:Object FF:function
console.log(varType(navigator)); //IE:DispHTMLNavigator FF:Navigator //以下幾個只適用于IE,其他內核瀏覽器不支持
if(!!window.VBArray){ console.log(varType(ActiveXObject)); //IE:function console.log(varType(Enumerator)); //IE:function console.log(varType(new ActiveXObject("Scripting.Dictionary"))); //IE:Dictionary console.log(varType(new Enumerator())); //IE:Enumerator
}將其放到html中,名為,代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>cookie生成測試</title>
</head>
<body>
<script type='text/javascript' src='http://www.abc.com/js/typeof_extend.js'></script>
</body>
</html>在chrome 39中測試如下:
在IE 11中測試如下:
參考文獻
[1].http://shenjc2008.iteye.com/blog/1009366
總結
以上是生活随笔為你收集整理的扩展typeof来判断js变量的类型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用windows.name解决js跨域
- 下一篇: 在Uubuntu 14.04 64bit