How do I tell difference between object and string in javascript?
I have a javscript function (actually a jQuery plugin) which I will want to call as either
myFunction("some input");
or
myFunction({ "prop": "value 1", "prop2": "value2" });
How do I, in the function, tell the two apart?
In other words, what should go in the if
conditions below?
if (/* the input is a string */)
{
/开发者_开发百科/ Handle string case (first of above)
}
else if (/* the input is an object */)
{
// Handle object case (second of above)
}
else
{
// Handle invalid input format
}
I have jQuery at my disposal.
Update: As noted in an answer, if the input is new String('some string')
, typeof(input)
will return 'object'
. How do I test for new String('')
, so I can handle that the same way as ''
?
if( typeof input === 'string' ) {
// input is a string
}
else if( typeof input === 'object' ) {
// input is an object
}
else {
// input is something else
}
Note that typeof
considers also arrays and null to be objects:
typeof null === 'object'
typeof [ 1, 2 ] === 'object'
If the distinction is important (you want only "actual" objects):
if( typeof input === 'string' ) {
// input is a string
}
else if( input && typeof input === 'object' && !( input instanceof Array ) ) {
// input is an object
}
else {
// input is something else
}
jQuery.type may be interesting to you.
if($.type(input)==='string')
{
//it's a string
}
As others have said, the typeof
operator will determine the type of the variable.
Beware though:
var str = 'A String' ;
var obj = new String(str) ;
console.log(typeof str) ;
console.log(typeof obj) ;
// Outputs:
// string
// object
The typeof
operator may get you what you need. i.e.:
typeof(myobj) == 'string'
(IIRC)
You can;
function f(a) { print(typeof a) }
f({"prop": "value 1", "prop2": "value2" });
>>object
f("Some input");
>>string
In javascript the command typeof
returns the type of the variable.
I created a little jsfiddle It seems that the array returns also typeof as an object.
<script>
var a = {'a':'b'};
if(typeof(a) == 'object'){
alert('object');
}
elseif(typeof(a) == 'string'){
alert('string');
}
</script>
http://forums.devx.com/showthread.php?t=5280
You can use the typeof
function:
if (typeof(myvar) === 'string') {
// the code
}
see here for more information
You want to use $.type, as this is more accurate than typeof
$.fn.plugin = function( options ) {
console.log( $.type( options ) );
if( $.type( options ) == 'string' ) {
// Handle string case (first of above)
}
else if( $.type( options ) == 'object' && options != null ) {
// Handle object case (second of above)
}
else {
// Handle invalid input format
}
};
$("#d1").plugin( new String('test')); //string
$("#d1").plugin('test'); //string
$("#d1").plugin({'key' : 'value'}); //object
Demo here
Edit
Also if options is not set then !options
would be sufficient
精彩评论