javascript中怎么判斷兩個數據類型相等


在 JavaScript 中,判斷一個變量的類型嘗嘗會用 typeof 運算符,在使用 typeof 運算符時采用引用類型存儲值會出現一個問題,無論引用的是什么類型的對象,它都返回 "object"。

所以怎么才能判斷兩個類型相等呢?

instanceof 來解決這個問題。instanceof 運算符與 typeof 運算符相似,用於識別正在處理的對象的類型。與 typeof 方法不同的是,instanceof 方法要求開發者明確地確認對象為某特定類型。例如:

var oStringObject = new String("hello world"); 
console.log(oStringObject instanceof String);   // 輸出 "true"

 下面是我簡單封裝了一下

                   第一種

function fn(arg1,arg2){
                   if(arg1===undefined||arg1===null){
                      console.log('無值')
                  }else{
                      if( arg2!=undefined||arg2!=null ){
                          console.log(2) 
                      }else{
                           if(typeof arg1 =='string'){
                               console.log(1) 
                           }
                           if( arg1 instanceof Array ){
                                        console.log(4) 
                               }
                            if( arg1 instanceof Object ){
                                         console.log(3) 
                            }
                          
                      }
                      
                  }
                
            }
            fn('hello');
            fn({});
            fn([]);
            fn();
            fn('hello','world');

第二種

 


免責聲明!

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



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