【发布时间】:2014-05-04 20:34:27
【问题描述】:
比较相同 javascript 类型的两个变量的最佳方法是什么?:
I.E.
[] = ['1','2','3']
[] != {}
Number = Number
null = null
等等。等等
【问题讨论】:
标签: javascript typeof
比较相同 javascript 类型的两个变量的最佳方法是什么?:
I.E.
[] = ['1','2','3']
[] != {}
Number = Number
null = null
等等。等等
【问题讨论】:
标签: javascript typeof
如果只是比较类型,人们会认为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()
}
那你就可以了
toType([]) === toType(['1','2','3']); // true
toType([]) === toType({}); // false
toType(1) === toType(9999); // true
toType(null) === toType(null); // true
toType(null) === toType([]); // false
【讨论】:
object 类型,所以它们与toType() 相同。你不能真正比较对象,因为两个对象永远不会相同,即使{} == {} 也会是错误的,因为两个对象永远不会相等,即使它们包含相同的东西。
如果您想区分对象“类型”,最好比较它们的原型:
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;
}
【讨论】:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
typeof 5 === typeof 37
typeof {} === typeof []
【讨论】:
这应该适用于所有“类型”:
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)
);
}
【讨论】: