亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

javascript中對(duì)變量類型的判斷

entner / 2644人閱讀

摘要:當(dāng)需要變量是否是類型時(shí),可以使用進(jìn)行判斷。本來(lái)是原型對(duì)象上的屬性,指向構(gòu)造函數(shù)。不過(guò)使用也不是保險(xiǎn)的,因?yàn)閷傩允强梢员恍薷牡?,?huì)導(dǎo)致檢測(cè)出的結(jié)果不正確,例如在上面的例子中,原型中的被修改為指向到,導(dǎo)致檢測(cè)不出實(shí)例對(duì)象真實(shí)的構(gòu)造函數(shù)。

在JavaScript中,有5種基本數(shù)據(jù)類型和1種復(fù)雜數(shù)據(jù)類型,基本數(shù)據(jù)類型有:Undefined, Null, Boolean, NumberString;復(fù)雜數(shù)據(jù)類型是Object,Object中還細(xì)分了很多具體的類型,比如:Array, Function, Date等等。今天我們就來(lái)探討一下,使用什么方法判斷一個(gè)出一個(gè)變量的類型。

在講解各種方法之前,我們首先定義出幾個(gè)測(cè)試變量,看看后面的方法究竟能把變量的類型解析成什么樣子,以下幾個(gè)變量差不多包含了我們?cè)趯?shí)際編碼中常用的類型。

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檢測(cè)

我們平時(shí)用的最多的就是用typeof檢測(cè)變量類型了。這次,我們也使用typeof檢測(cè)變量的類型:

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

從輸出的結(jié)果來(lái)看,arr, json, nul, date, reg, error 全部被檢測(cè)為object類型,其他的變量能夠被正確檢測(cè)出來(lái)。當(dāng)需要變量是否是number, string, boolean, function, undefined, json類型時(shí),可以使用typeof進(jìn)行判斷。其他變量是判斷不出類型的,包括null。

還有,typeof是區(qū)分不出arrayjson類型的。因?yàn)槭褂胻ypeof這個(gè)變量時(shí),array和json類型輸出的都是object。

2. 使用instance檢測(cè)

在 JavaScript 中,判斷一個(gè)變量的類型嘗嘗會(huì)用 typeof 運(yùn)算符,在使用 typeof 運(yùn)算符時(shí)采用引用類型存儲(chǔ)值會(huì)出現(xiàn)一個(gè)問(wèn)題,無(wú)論引用的是什么類型的對(duì)象,它都返回 "object"。ECMAScript 引入了另一個(gè) Java 運(yùn)算符 instanceof 來(lái)解決這個(gè)問(wèn)題。instanceof 運(yùn)算符與 typeof 運(yùn)算符相似,用于識(shí)別正在處理的對(duì)象的類型。與 typeof 方法不同的是,instanceof 方法要求開(kāi)發(fā)者明確地確認(rèn)對(duì)象為某特定類型。例如:

function Person(){

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

我們?cè)倏纯聪旅娴睦樱?/p>

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還能檢測(cè)出多層繼承的關(guān)系。

好了,我們來(lái)使用instanceof檢測(cè)上面的那些變量:

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

從上面的運(yùn)行結(jié)果我們可以看到,num, str和bool沒(méi)有檢測(cè)出他的類型,但是我們使用下面的方式創(chuàng)建num,是可以檢測(cè)出類型的:

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

同時(shí),我們也要看到,und和nul是檢測(cè)不成Object類型的,其他的類型也不對(duì),因此,若要使用instanceof進(jìn)行變量檢測(cè)時(shí),需要首先判斷是否是undefined和null。

3. 使用constructor檢測(cè)

在使用instanceof檢測(cè)變量類型時(shí),我們是檢測(cè)不到number, "string", bool的類型的。因此,我們需要換一種方式來(lái)解決這個(gè)問(wèn)題。

constructor本來(lái)是原型對(duì)象上的屬性,指向構(gòu)造函數(shù)。但是根據(jù)實(shí)例對(duì)象尋找屬性的順序,若實(shí)例對(duì)象上沒(méi)有實(shí)例屬性或方法時(shí),就去原型鏈上尋找,因此,實(shí)例對(duì)象也是能使用constructor屬性的。

我們先來(lái)輸出一下num.constructor的內(nèi)容,即數(shù)字類型的變量的構(gòu)造函數(shù)是什么樣子的:

function Number() { [native code] }

我們可以看到它指向了Number的構(gòu)造函數(shù),因此,我們可以使用num.constructor==Number來(lái)判斷num是不是Number類型的,其他的變量也類似:

function Person(){

}
var Tom = new Person();

// undefined和null沒(méi)有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
);
// 所有結(jié)果均為true

從輸出的結(jié)果我們可以看出,除了undefined和null,其他類型的變量均能使用constructor判斷出類型。

不過(guò)使用constructor也不是保險(xiǎn)的,因?yàn)閏onstructor屬性是可以被修改的,會(huì)導(dǎo)致檢測(cè)出的結(jié)果不正確,例如:

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,導(dǎo)致檢測(cè)不出實(shí)例對(duì)象John真實(shí)的構(gòu)造函數(shù)。

同時(shí),使用instaceof和construcor,被判斷的array必須是在當(dāng)前頁(yè)面聲明的!比如,一個(gè)頁(yè)面(父頁(yè)面)有一個(gè)框架,框架中引用了一個(gè)頁(yè)面(子頁(yè)面),在子頁(yè)面中聲明了一個(gè)array,并將其賦值給父頁(yè)面的一個(gè)變量,這時(shí)判斷該變量,Array == object.constructor;會(huì)返回false;
原因:
1、array屬于引用型數(shù)據(jù),在傳遞過(guò)程中,僅僅是引用地址的傳遞。
2、每個(gè)頁(yè)面的Array原生對(duì)象所引用的地址是不一樣的,在子頁(yè)面聲明的array,所對(duì)應(yīng)的構(gòu)造函數(shù),是子頁(yè)面的Array對(duì)象;父頁(yè)面來(lái)進(jìn)行判斷,使用的Array并不等于子頁(yè)面的Array;切記,不然很難跟蹤問(wèn)題!

4. 使用Object.prototype.toString.call

我們先不管這個(gè)是什么,先來(lái)看看他是怎么檢測(cè)變量類型的:

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]"

從輸出的結(jié)果來(lái)看,Object.prototype.toString.call(變量)輸出的是一個(gè)字符串,字符串里有一個(gè)數(shù)組,第一個(gè)參數(shù)是Object,第二個(gè)參數(shù)就是這個(gè)變量的類型,而且,所有變量的類型都檢測(cè)出來(lái)了,我們只需要取出第二個(gè)參數(shù)即可?;蛘呖梢允褂?b>Object.prototype.toString.call(arr)=="object Array"來(lái)檢測(cè)變量arr是不是數(shù)組。

我們現(xiàn)在再來(lái)看看ECMA里是是怎么定義Object.prototype.toString.call的:

Object.prototype.toString( ) When the toString method is called, the following steps are taken:

Get the [[Class]] property of this object.

Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.

Return Result (2)

上面的規(guī)范定義了Object.prototype.toString的行為:首先,取得對(duì)象的一個(gè)內(nèi)部屬性[[Class]],然后依據(jù)這個(gè)屬性,返回一個(gè)類似于"[object Array]"的字符串作為結(jié)果(看過(guò)ECMA標(biāo)準(zhǔn)的應(yīng)該都知道,[[]]用來(lái)表示語(yǔ)言內(nèi)部用到的、外部不可直接訪問(wèn)的屬性,稱為“內(nèi)部屬性”)。利用這個(gè)方法,再配合call,我們可以取得任何對(duì)象的內(nèi)部屬性[[Class]],然后把類型檢測(cè)轉(zhuǎn)化為字符串比較,以達(dá)到我們的目的。

5. jquery中$.type的實(shí)現(xiàn)

在jquery中提供了一個(gè)$.type的接口,來(lái)讓我們檢測(cè)變量的類型:

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

看到輸出結(jié)果,有沒(méi)有一種熟悉的感覺(jué)?對(duì),他就是上面使用Object.prototype.toString.call(變量)輸出的結(jié)果的第二個(gè)參數(shù)呀。

我們這里先來(lái)對(duì)比一下上面所有方法檢測(cè)出的結(jié)果,橫排是使用的檢測(cè)方法, 豎排是各個(gè)變量:

類型判斷 typeof instanceof constructor toString.call $.type
num number false true [object Number] number
str string false true [object String] string
bool boolean false true [object Boolean] boolean
arr object true true [object Array] array
json object true true [object Object] object
func function true true [object Function] function
und undefined false - [object Undefined] undefined
nul object false - [object Null] null
date object true true [object Date] date
reg object true true [object RegExp] regexp
error object true true [object Error] error
優(yōu)點(diǎn) 使用簡(jiǎn)單,能直接輸出結(jié)果 能檢測(cè)出復(fù)雜的類型 基本能檢測(cè)出所有的類型 檢測(cè)出所有的類型 -
缺點(diǎn) 檢測(cè)出的類型太少 基本類型檢測(cè)不出,且不能跨iframe 不能跨iframe,且constructor易被修改 IE6下undefined,null均為Object -
這樣對(duì)比一下,就更能看到各個(gè)方法之間的區(qū)別了,而且Object.prototype.toString.call$type輸出的結(jié)果真的很像。我們來(lái)看看jquery(2.1.2版本)內(nèi)部是怎么實(shí)現(xiàn)$.type方法的: // 實(shí)例對(duì)象是能直接使用原型鏈上的方法的 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(); }); 我們先來(lái)看看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(); }); //循環(huán)之后,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" } 再來(lái)看看type方法: // type的實(shí)現(xiàn) type: function( obj ) { // 若傳入的是null或undefined,則直接返回這個(gè)對(duì)象的字符串 // 即若傳入的對(duì)象obj是undefined,則返回"undefined" if ( obj == null ) { return obj + ""; } // Support: Android<4.0, iOS<6 (functionish RegExp) // 低版本regExp返回function類型;高版本已修正,返回object類型 // 若使用typeof檢測(cè)出的obj類型是object或function,則返回class2type的值,否則返回typeof檢測(cè)的類型 return (typeof obj === "object" || typeof obj === "function") ? (class2type[ toString.call(obj) ] || "object") : typeof obj; } 當(dāng)typeof obj === "object" || typeof obj === "function"時(shí),就返回class2type[ toString.call(obj)。到這兒,我們就應(yīng)該明白為什么Object.prototype.toString.call和$.type那么像了吧,其實(shí)jquery中就是用Object.prototype.toString.call實(shí)現(xiàn)的,把"[object Boolean]"類型轉(zhuǎn)成"boolean"類型并返回。若class2type存儲(chǔ)的沒(méi)有這個(gè)變量的類型,那就返回"object"。 除了"object"和"function"類型,其他的類型則使用typeof進(jìn)行檢測(cè)。即number, string, boolean類型的變量,使用typeof即可。

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/85786.html

相關(guān)文章

  • js中對(duì)數(shù)據(jù)類型總結(jié)及判斷數(shù)據(jù)類型各種方法及優(yōu)缺點(diǎn)

    摘要:最常見(jiàn)的判斷方法它的官方解釋操作符返回一個(gè)字符串,表示未經(jīng)計(jì)算的操作數(shù)的類型。另外,是判斷對(duì)象是否屬于某一類型,而不是獲取的對(duì)象的類型。多個(gè)窗口意味著多個(gè)全局環(huán)境,不同的全局環(huán)境擁有不同的全局對(duì)象,從而擁有不同的內(nèi)置類型構(gòu)造函數(shù)。 js中的數(shù)據(jù)類型 js中只有六種原始數(shù)據(jù)類型和一個(gè)Object: Boolean Null Undefined Number String Symbol ...

    voyagelab 評(píng)論0 收藏0
  • JavaScript-原始值和引用值

    摘要:一原始值和引用值的概念在中,變量可以存在兩種類型的值,即原始值和引用值。二棧和堆原始值存儲(chǔ)在棧中為變量賦值時(shí),的解釋程序必須判斷該值是原始類型,還是引用類型。 一、原始值和引用值的概念 在 ECMAScript 中,變量可以存在兩種類型的值,即原始值和引用值。 1.1 原始值 (1)原始值指的是 原始類型 的值,也叫 基本類型,例如 Number、Stirng、Boolean、Null...

    EsgynChina 評(píng)論0 收藏0
  • 理解JavaScript核心知識(shí)點(diǎn):This

    摘要:關(guān)鍵字計(jì)算為當(dāng)前執(zhí)行上下文的屬性的值。毫無(wú)疑問(wèn)它將指向了這個(gè)前置的對(duì)象。構(gòu)造函數(shù)也是同理。嚴(yán)格模式無(wú)論調(diào)用位置,只取顯式給定的上下文綁定的,通過(guò)方法傳入的第一參數(shù),否則是。其實(shí)并不屬于特殊規(guī)則,是由于各種事件監(jiān)聽(tīng)定義方式本身造成的。 this 是 JavaScript 中非常重要且使用最廣的一個(gè)關(guān)鍵字,它的值指向了一個(gè)對(duì)象的引用。這個(gè)引用的結(jié)果非常容易引起開(kāi)發(fā)者的誤判,所以必須對(duì)這個(gè)關(guān)...

    TerryCai 評(píng)論0 收藏0
  • [JavaScript 隨筆] 理解嚴(yán)格相等、非嚴(yán)格相等和隱式類型轉(zhuǎn)換

    摘要:顯然,相等判斷是基于數(shù)字比較的,而條件判斷是基于布爾值。嚴(yán)格相等嚴(yán)格相等的邏輯相對(duì)簡(jiǎn)單粗暴,如果類型不同,就不考慮隱式轉(zhuǎn)換了,直接為假。 JavaScript 中大概有這幾種 類型: undefined null string boolean number object function 之所以在 類型 上加了雙引號(hào),是因?yàn)閲?yán)格來(lái)說(shuō),null 的類型是 object。但本文討論的主...

    rickchen 評(píng)論0 收藏0
  • JavaScript基礎(chǔ)系列--數(shù)據(jù)類型類型判斷

    摘要:中有五種基本數(shù)據(jù)類型,以及一種復(fù)雜引用類型數(shù)據(jù)類型,中還細(xì)分了很多具體的類型,比如等等中又新增了一種類型。類型的數(shù)值范圍是,超出這個(gè)范圍的值為,可以使用函數(shù)來(lái)判斷數(shù)值是否在范圍內(nèi)。 ECMAScript5中有五種基本數(shù)據(jù)類型:Undefined,Null,Boolean,Number,String,以及一種復(fù)雜(引用類型)數(shù)據(jù)類型:Object,Object中還細(xì)分了很多具體的類型,比...

    duan199226 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<