JavaScript typeof obj === ‘object’ 這樣寫有什么問題


typeof Array, Object, new Class() 都會返回'object', 所以使用typeof不能准確的判斷變量是否為object

typeof [];  //object
typeof {};  //object
typeof new (function (){});  //object
typeof 1//number
typeof '1'//string
typeof null//object
typeof true//boolean
 
 要 准確判斷一個變量是否是一個對象,可以使用constructor以及instanceof判斷。
1. constructor是指該對象的構造函數, 使用constructor時, 要注意, 實例化類時, 類的prototype.constructor需要正確引用。
({}).constructor === Object;  //true
(1).constructor === Number;  //true
([]).constructor === Array;  //true
('1').constructor === String;  //true
(true).constructor === Boolean;  //true

 

2. instanceof是指該對象是否為指定類的實例
({}) instanceof Object;  //true
([]) instanceof Array;   //true
(1) instanceof Number;  //true
('1') instanceof String;  //true
(true) instanceof Boolean;  //true

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM