js中typeof和instanceof用法區別

來源:互聯網
上載者:User

標籤:系統   instance   瀏覽器   lib   cto   bool   boolean   個數   ==   

typeof和instanceof的區別

typeof和instanceof都可以用來判斷變數,它們的用法有很大區別:

typeof會返回一個變數的基本類型,只有以下幾種:number,boolean,string,object,undefined,function;例:

alert(typeof(1));//number

alert(typeof("abc"));//string

alert(typeof(true));//boolean

alert(typeof(m));//undefined

如果我們想要判斷一個變數是否存在,可以使用typeof:(不能使用if(a) 若a未聲明,則報錯)

if(typeof a != ‘undefined‘){

    //變數存在

}

instanceof返回的是一個布爾值,如:

var a = {};

alert(a instanceof Object);  //true

var b = [];

alert(b instanceof Array);  //true

需要注意的是,instanceof只能用來判斷對象和函數,不能用來判斷字串和數字等,如:

var b = ‘123‘;

alert(b instanceof String);  //false

alert(typeof b);  //string

var c = new String("123");

alert(c instanceof String);  //true

alert(typeof c);  //object

另外,用instanceof可以判斷變數是否為數組

 

大家都知道js中可以使用typeof來判斷變數的基本類型,如:

alert(typeof ‘111‘); // "string" 

alert(typeof 22); // "number" 

alert(typeof a); // "undefined" 

alert(typeof undefined); // "undefined" 

alert(typeof []); // "object"

但是這個方法不適用於來判斷數組,因為不管是數組還是對象,都會返回object,這就需要我們需求其他的方法。

有幾種方法可以拿來判斷:

1、constructor屬性

這個屬性在我們使用js系統或者自己建立的對象的時候,會預設的加上,例如:

var arr = [1,2,3];  //建立一個數組對象

arr.prototype.constructor = Array;  //這一句是系統預設加上的

所以我們就可以這樣來判斷:

var arr = [1,2,3,1]; 

alert(arr.constructor === Array);   // true

2、instanceof

instanceof是檢測對象的原型鏈是否指向建構函式的prototype對象的,所以我們也可以用它來判斷:

 

var arr = [1,2,3]; 

alert(arr instanceof Array);   // true

 

最後,為了給大家一個結果,現寫出一個終極解決方案:

判斷數組終極解決方案

var arr = [1,2,3]; 

function isArrayFn(obj){  //封裝一個函數

if (typeof Array.isArray === "function") { 

return Array.isArray(obj); //瀏覽器支援則使用isArray()方法

}else{                     //否則使用toString方法

return Object.prototype.toString.call(obj) === "[object Array]"; 

alert(isArrayFn(arr));// true

js中typeof和instanceof用法區別

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.