简体   繁体   中英

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

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]);

If having a list of variables is mandatory you could use eval() like this:

$(element).html(eval("subcatlist"+ itemNumber));

eval can be harmful and should be avoided when dealing with user input, if possible I'd use the solution proposed by Sudharsan

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM