js 判斷資料類型

來源:互聯網
上載者:User

標籤:define   封裝   str   建立   使用   var   efi   cto   tor   

var a = {};
var b = [];
var c = null;
var d = ‘‘;
var e = undefined;

var aa = (typeof a === ‘object‘);
var bb = (typeof b === ‘object‘);
var cc = (typeof c === ‘object‘);
var dd = (typeof d === ‘object‘);
var ee = (typeof e === ‘object‘)

var f = [aa,bb,cc,dd,ee];

console.log(f);

>: [true, true, true, false, false]

var aa = (typeof a === ‘object‘); 
var bb = (typeof b === ‘object‘); 
var cc = (typeof c === ‘object‘); 
var dd = (typeof d === ‘string‘); 
var ee = (typeof e === ‘undefined‘)

var f = [aa,bb,cc,dd,ee];

console.log(f);

>: [true, true, true, true, true]

推論:‘’及undefined的typeof不是Object,而是string及undefined類型

var aa = a instanceof Object;
var bb = b instanceof Object;
var cc = c instanceof Object;
var dd = d instanceof Object;
var ee = e instanceof Object;

var f = [aa,bb,cc,dd,ee];

console.log(f);

>: [true, true, false, false, false]

var aa = a instanceof Object; 
var bb = b instanceof Object; 
var cc = c instanceof Object; 
var dd = d instanceof Object; 
var ee = e instanceof Object; 

var f = [aa,bb,cc,dd,ee];

console.log(f);

>: [true, true, false, false, false]

console.log(c instanceof null)
>: 拋出錯誤

console.log(d instanceof String)

>: false

console.log(new String(‘123‘) instanceof String)

>: true

console.log(e instanceof undefined)

>: false

推論:instanceof 僅用於判斷對象是否屬於指定對象的執行個體,null不是任何對象的執行個體;單一資料型別如bool、number、string、undefined均不是其他對象的執行個體,因此不能使用instanceof運算子判斷,但是,顯式的使用基本封裝類型建立的對象則可以使用instanceof判斷出具體類型;

var aa = a.constructor.name;
var bb = b.constructor.name;
var cc = c.constructor.namet;
var dd = d.constructor.name;
var ee = e .constructor.name;
var f = [aa,bb,cc,dd,ee];
console.log(f);

>:["Object", "Array", 錯誤, "String", 錯誤]

錯誤都是因為null和undefined並無構造子引起的;

 

js 判斷資料類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.