2014-05-04 143 views
0

對於相同的javascript類型,比較兩個變量的最佳方法是什麼:Javascript類型比較

I.E.

[] = ['1','2','3'] 
[] != {} 
Number = Number 
null = null 

等等,等等

回答

4

要只是比較類型,人們會認爲typeof將是合適的工具

typeof [] === typeof ['1','2','3']; // true, both are arrays 

注意null,陣列等都是'object'型的,這意味着

typeof [] === typeof null; // is true (both are objects) 
typeof [] === typeof {}; // is true (both are objects) 

這是預期的行爲我們的。

如果你有專門檢查null,數組或其他東西,你可以只寫一個更好的typeof功能

var toType = function(obj) { 
    return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase() 
} 

FIDDLE

那麼你可以做

toType([]) === toType(['1','2','3']); // true 
toType([]) === toType({});  // false 
toType(1) === toType(9999); // true 
toType(null) === toType(null); // true 
toType(null) === toType([]); // false 
+0

喜歡它!確切地說我在找什麼 - 在我的測試中,這是一個隨機的想法。怎麼樣功能測試(){} toType(新測試());哪些會出現爲對象? – Corey

+0

應該返回'object' - > ** http://jsfiddle.net/DUk96/1/** – adeneo

+0

是的,但是:function test1(){} && test2(){}將相互平等toType(new test1 ))== toType(new test2()); - 我真的不需要這個壽,只是好奇 - 其實不用擔心,哈哈,我很好。謝謝你的幫助! – Corey

0

這應該爲所有的「類型」的工作:

function haveSameType(a,b) { 
    return (a instanceof Array && b instanceof Array) || 
    (a === null && b === null) || 
    (typeof a === typeof b && 
    b !== null && 
    a !== null && 
    ! (a instanceof Array) && 
    ! (b instanceof Array) 
    ); 
} 
0

如果你想從彼此區分對象「類型」,這可能是一個好主意,比較它們的原型:

Object.getPrototypeOf([]) === Object.getPrototypeOf([1, 2, 3]) 
Object.getPrototypeOf({}) !== Object.getPrototypeOf([]) 

然而,如果你沒有傳入對象,這會拋出,所以如果你還想比較原始值的類型(包括null),你將不得不做更復雜的測試:

function sameType(a, b) { 
    var objectA = Object(a) === a, 
     objectB = Object(b) === b; 
    if (objectA && objectB) 
     return Object.getPrototypeOf(a) === Object.getPrototypeOf(b); 
    else if (!objectA && !objectB) 
     return typeof a === typeof b; 
    else 
     return false; 
}