Checking the type of a variable
What's the best way to find out whether a variable is a string or not (and, likewise, a number, a boolean, etc.)?
Usually you will find:
function isString(value) {
return typeof value === 'string';
}
But people forget that one can also create string objects directly using var foo = new String("bar");
- whether that is a good idea or not is an entirely different matter.
So what's the way to go here? I can think of - and have seen - various approaches (somewhat simplified):
// option 1
function isString(value) {
return (typeof value === 'string') ||
/^function String\(\)/.test(value.constructor + '');
}
or
// option 2
function isString(value) {
return (ty开发者_高级运维peof value === 'string') ||
(value.constructor === String);
}
or
// option 3
function isString(value) {
return (typeof value === 'string') ||
value instanceof String;
}
Is there a "best" way to go about this? Or are they all equivalent?
Among the three existing options, the first feels rather hacky to me because it uses a regular expression to test the string representation of value.constructor
. It works, but it still feels hacky (maybe it's just me).
The second option would only work for string literals, strings created from concatenating existing objects and objects made with the new String()
constructor, whereas the third option should work with objects made with the new String()
constructor or any other object that inherits from String()
(I'm not sure about JavaScript inheritance; can someone confirm this?).
The constructor
property exists also for primitives/literals, not just wrapper objects created using new
. This makes the typeof
check in the second option quite redundant:
function isString(value) {
return value.constructor === String;
}
alert(isString("test1")); // true
alert(isString(new String("test2"))); // true
However, unlike the third option it may not work with objects with constructors other than String()
that inherit from String()
.
My answer uses strings as an example to reflect the question but the same idea applies to Number
, Boolean
, Function
, Object
, Array
and other types.
精彩评论