日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

javascript中对变量类型的推断

發布時間:2023/11/29 javascript 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 javascript中对变量类型的推断 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文正式地址:http://www.xiabingbao.com/javascript/2015/07/04/javascript-type

在JavaScript中,有5種基本數據類型和1種復雜數據類型,基本數據類型有:Undefined,?Null,?Boolean,?NumberString。復雜數據類型是Object。Object中還細分了非常多詳細的類型,比方:Array,?Function,?Date等等。今天我們就來探討一下,使用什么方法推斷一個出一個變量的類型。

在解說各種方法之前。我們首先定義出幾個測試變量,看看后面的方法到底能把變量的類型解析成什么樣子,以下幾個變量差點兒相同包括了我們在實際編碼中經常使用的類型。

var num = 123; var str = 'abcdef'; var bool = true; var arr = [1, 2, 3, 4]; var json = {name:'wenzi', age:25}; var func = function(){ console.log('this is function'); } var und = undefined; var nul = null; var date = new Date(); var reg = /^[a-zA-Z]{5,20}$/; var error= new Error();

1. 使用typeof檢測

我們平時用的最多的就是用typeof檢測變量類型了。

這次,我們也使用typeof檢測變量的類型:

console.log(typeof num, typeof str, typeof bool, typeof arr, typeof json, typeof func, typeof und, typeof nul, typeof date, typeof reg, typeof error ); // number string boolean object object function undefined object object object object

從輸出的結果來看,arr, json, nul, date, reg, error 全部被檢測為object類型。其它的變量能夠被正確檢測出來。當須要變量是否是number,?string,?boolean,?function,?undefined, json類型時。能夠使用typeof進行推斷。其它變量是推斷不出類型的,包括null。

還有。typeof是區分不出array和json類型的。由于使用typeof這個變量時,array和json類型輸出的都是object。

2. 使用instance檢測

在 JavaScript 中,推斷一個變量的類型嘗嘗會用 typeof 運算符。在使用 typeof 運算符時採用引用類型存儲值會出現一個問題,不管引用的是什么類型的對象,它都返回 “object”。ECMAScript 引入了還有一個 Java 運算符 instanceof 來解決問題。instanceof 運算符與 typeof 運算符相似,用于識別正在處理的對象的類型。

與 typeof 方法不同的是,instanceof 方法要求開發人員明白地確認對象為某特定類型。

比如:

function Person(){} var Tom = new Person(); console.log(Tom instanceof Person); // true

我們再看看以下的樣例:

function Person(){} function Student(){} Student.prototype = new Person(); var John = new Student(); console.log(John instanceof Student); // true console.log(John instancdof Person); // true

instanceof還能檢測出多層繼承的關系。

好了。我們來使用instanceof檢測上面的那些變量:

console.log(num instanceof Number,str instanceof String,bool instanceof Boolean,arr instanceof Array,json instanceof Object,func instanceof Function,und instanceof Object,nul instanceof Object,date instanceof Date,reg instanceof RegExp,error instanceof Error ) // num : false // str : false // bool : false // arr : true // json : true // func : true // und : false // nul : false // date : true // reg : true // error : true

從上面的執行結果我們能夠看到,num, str和bool沒有檢測出他的類型,可是我們使用以下的方式創建num,是能夠檢測出類型的:

var num = new Number(123); var str = new String('abcdef'); var boolean = new Boolean(true);

同一時候,我們也要看到,und和nul是檢測的Object類型,才輸出的true,由于js中沒有Undefined和Null的這樣的全局類型,他們und和nul都屬于Object類型,因此輸出了true。

3. 使用constructor檢測

在使用instanceof檢測變量類型時。我們是檢測不到number, ‘string’,?bool的類型的。

因此,我們須要換一種方式來解決問題。

constructor本來是原型對象上的屬性,指向構造函數。可是根據實例對象尋找屬性的順序,若實例對象上沒有實例屬性或方法時,就去原型鏈上尋找,因此,實例對象也是能使用constructor屬性的。

我們先來輸出一下num.constructor的內容,即數字類型的變量的構造函數是什么樣子的:

function Number() { [native code] }

我們能夠看到它指向了Number的構造函數。因此,我們能夠使用num.constructor==Number來推斷num是不是Number類型的。其它的變量也相似:

function Person(){} var Tom = new Person();// undefined和null沒有constructor屬性 console.log(Tom.constructor==Person,num.constructor==Number,str.constructor==String,bool.constructor==Boolean,arr.constructor==Array,json.constructor==Object,func.constructor==Function,date.constructor==Date,reg.constructor==RegExp,error.constructor==Error ); // 全部結果均為true

從輸出的結果我們能夠看出,除了undefined和null。其它類型的變量均能使用constructor推斷出類型。

不過使用constructor也不是保險的,由于constructor屬性是能夠被改動的,會導致檢測出的結果不對,比如:

function Person(){} function Student(){} Student.prototype = new Person(); var John = new Student(); console.log(John.constructor==Student); // false console.log(John.constructor==Person); // true

在上面的樣例中,Student原型中的constructor被改動為指向到Person,導致檢測不出實例對象John真實的構造函數。

同一時候,使用instaceof和construcor,被推斷的array必須是在當前頁面聲明的!比方。一個頁面(父頁面)有一個框架,框架中引用了一個頁面(子頁面),在子頁面中聲明了一個array,并將其賦值給父頁面的一個變量。這時推斷該變量。Array == object.constructor;會返回false;?
原因:?
1、array屬于引用型數據。在傳遞過程中。不過引用地址的傳遞。?
2、每一個頁面的Array原生對象所引用的地址是不一樣的,在子頁面聲明的array,所相應的構造函數。是子頁面的Array對象。父頁面來進行推斷,使用的Array并不等于子頁面的Array。切記。不然非常難跟蹤問題!

4. 使用Object.prototype.toString.call

我們先不管這個是什么,先來看看他是怎么檢測變量類型的:

console.log(Object.prototype.toString.call(num),Object.prototype.toString.call(str),Object.prototype.toString.call(bool),Object.prototype.toString.call(arr),Object.prototype.toString.call(json),Object.prototype.toString.call(func),Object.prototype.toString.call(und),Object.prototype.toString.call(nul),Object.prototype.toString.call(date),Object.prototype.toString.call(reg),Object.prototype.toString.call(error) ); // '[object Number]' '[object String]' '[object Boolean]' '[object Array]' '[object Object]' // '[object Function]' '[object Undefined]' '[object Null]' '[object Date]' '[object RegExp]' '[object Error]'

從輸出的結果來看,Object.prototype.toString.call(變量)輸出的是一個字符串,字符串里有一個數組,第一個參數是Object,第二個參數就是這個變量的類型,并且,全部變量的類型都檢測出來了,我們只須要取出第二個參數就可以。

或者能夠使用Object.prototype.toString.call(arr)=="object Array"來檢測變量arr是不是數組。

我們如今再來看看ECMA里是是怎么定義Object.prototype.toString.call的:

Object.prototype.toString( ) When the toString method is called, the following steps are taken:?
1. Get the [[Class]] property of this object.?
2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.?
3. Return Result (2)

上面的規范定義了Object.prototype.toString的行為:首先,取得對象的一個內部屬性[[Class]],然后根據這個屬性,返回一個相似于”[object Array]”的字符串作為結果(看過ECMA標準的應該都知道,[[]]用來表示語言內部用到的、外部不可直接訪問的屬性。稱為“內部屬性”)。利用這種方法,再配合call,我們能夠取得不論什么對象的內部屬性[[Class]]。然后把類型檢測轉化為字符串比較,以達到我們的目的。

5. jquery中$.type的實現

在jquery中提供了一個$.type的接口,來讓我們檢測變量的類型:

console.log($.type(num),$.type(str),$.type(bool),$.type(arr),$.type(json),$.type(func),$.type(und),$.type(nul),$.type(date),$.type(reg),$.type(error) ); // number string boolean array object function undefined null date regexp error

看到輸出結果,有沒有一種熟悉的感覺?對,他就是上面使用Object.prototype.toString.call(變量)輸出的結果的第二個參數呀。

我們這里先來對照一下上面全部方法檢測出的結果,橫排是使用的檢測方法, 豎排是各個變量:

類型推斷typeofinstanceofconstructortoString.call$.type
numnumberfalsetrue[object Number]number
strstringfalsetrue[object String]string
boolbooleanfalsetrue[object Boolean]boolean
arrobjecttruetrue[object Array]array
jsonobjecttruetrue[object Object]object
funcfunctiontruetrue[object Function]function
undundefinedfalse-[object Undefined]undefined
nulobjectfalse-[object Null]null
dateobjecttruetrue[object Date]date
regobjecttruetrue[object RegExp]regexp
errorobjecttruetrue[object Error]error
長處使用簡單,能直接輸出結果能檢測出復雜的類型基本能檢測出全部的類型檢測出全部的類型-
缺點檢測出的類型太少基本類型檢測不出,且不能跨iframe不能跨iframe,且constructor易被改動IE6下undefined,null均為Object-

這樣對照一下,就更能看到各個方法之間的差別了,并且Object.prototype.toString.call和$type輸出的結果真的非常像。我們來看看jquery(2.1.2版本號)內部是怎么實現$.type方法的:

// 實例對象是能直接使用原型鏈上的方法的 var class2type = {}; var toString = class2type.toString;// 省略部分代碼...type: function( obj ) {if ( obj == null ) {return obj + "";}// Support: Android<4.0, iOS<6 (functionish RegExp)return (typeof obj === "object" || typeof obj === "function") ?(class2type[ toString.call(obj) ] || "object") :typeof obj; },// 省略部分代碼... // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {class2type[ "[object " + name + "]" ] = name.toLowerCase(); });

我們先來看看jQuery.each的這部分:

// Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {class2type[ "[object " + name + "]" ] = name.toLowerCase(); });//循環之后,`class2type`的值是: class2type = {'[object Boolean]' : 'boolean', '[object Number]' : 'number','[object String]' : 'string','[object Function]': 'function','[object Array]' : 'array','[object Date]' : 'date','[object RegExp]' : 'regExp','[object Object]' : 'object','[object Error]' : 'error' }

再來看看type方法:

// type的實現 type: function( obj ) {// 若傳入的是null或undefined。則直接返回這個對象的字符串// 即若傳入的對象obj是undefined。則返回"undefined"if ( obj == null ) {return obj + "";}// Support: Android<4.0, iOS<6 (functionish RegExp)// 低版本號regExp返回function類型;高版本號已修正,返回object類型// 若使用typeof檢測出的obj類型是object或function。則返回class2type的值,否則返回typeof檢測的類型return (typeof obj === "object" || typeof obj === "function") ?(class2type[ toString.call(obj) ] || "object") :typeof obj; }

當typeof obj === "object" || typeof obj === "function"時,就返回class2type[ toString.call(obj)。

到這兒,我們就應該明白為什么Object.prototype.toString.call和$.type那么像了吧,事實上jquery中就是用Object.prototype.toString.call實現的。把’[object Boolean]’類型轉成’boolean’類型并返回。若class2type存儲的沒有這個變量的類型,那就返回”object”。?
除了”object”和”function”類型。其它的類型則使用typeof進行檢測。即number,?string,?boolean類型的變量,使用typeof就可以。

本文正式地址:http://www.xiabingbao.com/javascript/2015/07/04/javascript-type








本文轉自mfrbuaa博客園博客,原文鏈接:http://www.cnblogs.com/mfrbuaa/p/5202979.html,如需轉載請自行聯系原作者

總結

以上是生活随笔為你收集整理的javascript中对变量类型的推断的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。