我理解为什么你需要使用Object.prototype.toString()
或String()
进行类型检查数组,但对于类型检查函数和字符串来说typeof是否足够?例如,Array.isArray的MDN上的polyfill使用:
Object.prototype.toString.call(arg) == '[object Array]';
在数组的情况下非常清楚,因为您无法使用typeof
来检查数组。 Valentine使用instanceof:
ar instanceof Array
但是对于字符串/函数/布尔值/数字,为什么不使用typeof
?
jQuery和Underscore都使用类似的方法来检查功能:
Object.prototype.toString.call(obj) == '[object Function]';
这不等于这样做吗?
typeof obj === 'function'
甚至是这个?
obj instanceof Function
答案 0 :(得分:16)
好的,我想我找出了为什么你会看到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 :(得分: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。