I need to dynamical create a variable off the value of a variable from an argument I am pulling in from a script. But I first want to check if it already exists so I don't overwrite it, if it is already set.
I am leveraging eval to expand the value of the variable and tag it onto a variable suffix but no matter what I use to check for the undefined I am getting a reference error on the check.
Below is the simple code snippet
chkUser = args[1];
if(typeof eval(chkUser+"lastseen")==="undefined") ;
I've also tried put the eval in parens and putting undefined in ' ' and pulled them completely and switching typeof to the JavaScript standard undefined as such
if( eval(chkUser+"lastseen")=== undefined) ;
but I always get ReferenceError: robertlastseen is not defined or what ever chkUser expands out to.
Its just a guess, but it seems like the Variable is just not defined before you eval it.
try this Fiddle.
It works fine for me.
Try to hard-code the variable before you eval it like this:
chkUser = args[1];
var robertlastseen = 'Hardcode';
console.log(eval(chkUser+"lastseen"));
Then you should be able to debug your code.
if you just want to test if this Variable is declared try this:
if(eval('typeof ' + chkUser + 'lastseen') === "undefined"){
//Variable undefined
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With