2012-03-01 62 views
8

我明白你爲什麼需要使用Object.prototype.toString()String()的類型檢查數組,但不是typeof足夠的類型檢查功能和字符串?例如,對於Array.isArray上MDN的填充工具使用:爲什麼使用toString()來檢測可以用typeof檢查的參數?

Object.prototype.toString.call(arg) == '[object Array]'; 

它在陣列的情況很清楚,因爲你不能使用typeof檢查數組。 Valentine使用此instanceof

ar instanceof Array 

但字符串/功能/布爾/號碼,爲什麼不使用typeof

jQueryUnderscore都使用這樣的檢查功能:

Object.prototype.toString.call(obj) == '[object Function]'; 

是不是等同於這樣做呢?

typeof obj === 'function' 

甚至這個?

obj instanceof Function 

回答

15

好吧,我想我想通了,爲什麼你看到toString使用。試想一下:

var toString = Object.prototype.toString; 
var strLit = 'example'; 
var strStr = String('example')​; 
var strObj = new String('example'); 

console.log(typeof strLit); // string  
console.log(typeof strStr); // string 
console.log(typeof strObj); // object 

console.log(strLit instanceof String); // false 
console.log(strStr instanceof String); // false 
console.log(strObj instanceof String); // true 

console.log(toString.call(strLit)); // [object String] 
console.log(toString.call(strStr)); // [object String] 
console.log(toString.call(strObj)); // [object String] 

+1

請注意,它不適用於Promises,至少在Firefox的Chrome中。 'typeof mypromise ==='object','toString.call(mypromise)==='[Object]'',但'mypromise instanceof Promise === true' – Hurelu 2015-05-29 01:19:06

1

我能想到的第一個原因是typeof null回報object,這通常不是你想要的(因爲null是不是對象,但在它自己的權利的類型)。

然而,Object.prototype.toString.call(null)回報[object Null]

但是,正如你提到的,如果你希望的東西是一個字符串或其他類型與typeof效果很好,我看不出有任何理由,你爲什麼不能使用typeof(我經常這樣做在這種情況下使用typeof)。

另一個原因庫如你提到的那些使用他們選擇的方法可以簡單地是一致性。您可以使用typeof來檢查Array,所以請使用其他方法並堅持這一點。

對於一些詳細信息,Angus Croll has an excellent article on the typeof operator

+0

我談論檢查的東西似乎沒有像串/功能/布爾/數字順利應該工作 – ryanve 2012-03-01 08:17:54

+0

++尼斯鏈接:] – ryanve 2012-03-01 08:33:40

+0

請注意,它不與Promises一起工作,至少在Firefox中使用Firefox。 'typeof運算mypromise ===「object','toString.call(mypromise)=== [對象]'','不過的instanceof mypromise無極=== TRUE' – Hurelu 2015-05-29 01:15:15

相關問題