I have a function like:
function testFunction( option )
{
alert(option);
}
(the actual function does more than just answer the option)
And of course, it works if you do testFunction("qwerty");, or testFunction(myvar);, where myvar is a variable.
It does not work if I do testFunction(qwerty);, where qwerty is not a variable, as expected.
I was wondering if there is a way to make the function check to see if option is a variable or string (such as "qwerty" and myvar in the examples above) and if it is continue as normal and alert the string or the variable's value.
However, if it is not a variable or string, but is an undefined variable (such as qwerty in the example above) then I would like it to alert the name of the variable (qwerty in this case).
Is this possible?
Thanks!
Some more examples:
var myvar = "1234";
testFunction("test"); //alerts "test"
testFunction(myvar); //alerts "1234"
testFunction(qwerty); //alert "qwerty"
-
There is a question with (close to) exact same title available on SO. See SO question stackoverflow.com/questions/7983896/…Matthias– Matthias2014年10月05日 12:42:03 +00:00Commented Oct 5, 2014 at 12:42
-
No, it's not possible.user663031– user6630312014年10月05日 12:45:12 +00:00Commented Oct 5, 2014 at 12:45
-
What's the purpose of this anyway?xShirase– xShirase2014年10月05日 12:55:04 +00:00Commented Oct 5, 2014 at 12:55
-
That's an XY problem. Why do you want to do this? I've never come across a case where this was needed.plalx– plalx2014年10月05日 13:03:53 +00:00Commented Oct 5, 2014 at 13:03
-
xkcd.com/293xShirase– xShirase2014年10月05日 13:04:13 +00:00Commented Oct 5, 2014 at 13:04
1 Answer 1
Your problem here is that testFunction(qwerty); will not even reach the function.
Javascript cannot interpret the variable 'qwerty' as it is not defined, so it will crash right there.
Just for fun, here's a way to do what you request, by catching the error thrown when you try to interpret an undefined variable :
function testFunction( option ){
console.log(option);
}
try {
var myvar = "1234";
testFunction("test"); //alerts "test"
testFunction(myvar);
testFunction(qwerty); //alert "qwerty"
}catch(e){
if(e.message.indexOf('is not defined')!==-1){
var nd = e.message.split(' ')[0];
testFunction(nd);
}
}
Bear in mind that you should absolutely never do that, instead, try using existing variables in your programs, it works better ;)
Comments
Explore related questions
See similar questions with these tags.