0

In Javascript, I define global variables sld_label where label can be any string. These are initialised to objects that have a setval function. I need to check, within a function which is handed label in a string parameter called qq, whether sld_label has been defined. How do I do this without raising an error?

At the moment I have the following (which works but generates an error in Firebug) :-

function setclrques(qq,op)
{
  if (typeof(eval('sld_'+qq))=='object') eval('sld_'+qq+'.setval('+op+')');
}

Help!

1
  • 1
    This has been asked many times in SO. Commented Aug 29, 2012 at 10:39

4 Answers 4

1

If global then it ends up as member of window, so that the following works:

if (typeof window['sld_' + qq] == 'undefined') alert('sld_' + qq + ' is not defined.');
Sign up to request clarification or add additional context in comments.

3 Comments

if the variable has been defined as false or 0 (zero), the check will fail!
Ahh yes that is true, I'll fix it.
The key to it all was using window[...] for variable variable names! Thanks!
0

I implemented something like this.

function Test()
{
}

Test.prototype.setval = function(options)
{
    alert(options);
}

function setclrques(qq,op)
{
    var obj = window['sld_'+qq];
    if( obj!=undefined && obj.setval!=undefined )
    {
        obj.setval(op);
    }
}

var sld_qwer = new Test();
setclrques("qwer","test!");

However I'd recommend you to consider associative array instead of separate variables for storing the objects if possible:

function Test()
{
}

Test.prototype.setval = function(options)
{
    alert(options);
}

var sld = [];
sld["qwer"] = new Test();

function setclrques(qq,op)
{
    var obj = sld[qq];
    if( obj!=undefined && obj.setval!=undefined )
    {
        obj.setval(op);
    }
}

setclrques("qwer","test!");

1 Comment

Great suggestion! I didn't know JavaScript had support for associative arrays. Thanks!
0
if (typeof window["sld_" + qq] === "object") {
    window["sld_" + qq].setval(op);
}

1 Comment

This is the best solution because there is no call to "eval" - thanks!
0

If you want to check if a variable exist

if (typeof yourvar != 'undefined') // Any scope
if (window['varname'] != undefined) // Global scope
if (window['varname'] != void 0) // Old browsers

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.