Reputation: 3293
In JavaScript, I want to write a function that determines if the two variables passed in are of the same data type, such as string, integer, boolean etc. However, I have no idea as to how to compare the two variables in term of their DATA TYPES instead of the VALUES stored inside the variables.
Thank you in advance =)
Upvotes: 0
Views: 221
Reputation: 413712
You can use typeof
as suggested, but it's not perfect; an array and a Date instance will both be considered to be of type "object".
Another imperfect way to compare by type is this:
function sameTypes() {
var tp = null, ts = Object.prototype.toString;
if (arguments.length === 0) return true; // or false if you prefer
tp = ts.call(arguments[0]);
for (var i = 1; i < arguments.length; ++i)
if (tp !== ts.call(arguments[i])) return false;
return true;
}
You can pass that function two or more (well one or more I guess) values and it'll return true
if the result of calling the "toString" function on the Object prototype is the same for all of them. This one's not perfect because it promotes primitives to objects, so a string constant will seem to have the same type as a String instance.
Upvotes: 3
Reputation: 1665
Use typeof()
var test = true,
test2 = "string";
if (typeof(test) === typeof(test2)) {}
Upvotes: 0