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
    This has been asked many times in [SO](http://stackoverflow.com/questions/519145/how-can-i-check-whether-a-variable-is-defined-in-javascript). – The Alpha Aug 29 '12 at 10:39

4 Answers4

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.');
Lloyd
  • 29,197
  • 4
  • 84
  • 98
0
if (typeof window["sld_" + qq] === "object") {
    window["sld_" + qq].setval(op);
}
Andreas
  • 21,535
  • 7
  • 47
  • 56
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
pkurek
  • 606
  • 4
  • 13
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!");
Mikhail Payson
  • 923
  • 8
  • 12