对于相同的javascript类型,比较两个变量的最佳方法是什么:Javascript类型比较
I.E.
[] = ['1','2','3']
[] != {}
Number = Number
null = null
等等,等等
对于相同的javascript类型,比较两个变量的最佳方法是什么:Javascript类型比较
I.E.
[] = ['1','2','3']
[] != {}
Number = Number
null = null
等等,等等
要只是比较类型,人们会认为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
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)
);
}
如果你想从彼此区分对象“类型”,这可能是一个好主意,比较它们的原型:
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;
}
喜欢它!确切地说我在找什么 - 在我的测试中,这是一个随机的想法。怎么样功能测试(){} toType(新测试());哪些会出现为对象? – Corey
应该返回'object' - > ** http://jsfiddle.net/DUk96/1/** – adeneo
是的,但是:function test1(){} && test2(){}将相互平等toType(new test1 ))== toType(new test2()); - 我真的不需要这个寿,只是好奇 - 其实不用担心,哈哈,我很好。谢谢你的帮助! – Corey