Search code examples
javascriptjqueryvariables

javascript variable and value concatenation


I have a list of variables:

subcatlist1 = 'aa';
subcatlist2 = 'bb';
subcatlist3 = 'cc';

What i would like to do, is insert the value of a given variable from the option options, into an element, but the 'number' of the variable (ie, 1, 2 or 3) is itself coming in as a variable, say itemNumber.

What I would like to do is: $(element).html(subcatlist+ itemNumber);

... Which would give the value of aa for itemNumber = 1

The error that I am getting is: ReferenceError: subcatlist is not defined - which make sense, because the variable subcatlist doesn't exist - only subcatlist1, subcatlist2, subcatlist3 exist.

Do how can i concatenate the subcatlist+ itemNumber to get a variable that i can use, as subcatlist1 etc?

Thanks


Solution

  • Use object instead of variable is better approach in your context,Because you concadenate with variable is wrong.

    var subcatlist = {1:"aa",2:"bb",3:"cc"}
    
    $(element).html(subcatlist[itemNumber]);