Reputation: 914
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
Upvotes: 0
Views: 87
Reputation: 2408
Updated
The solution is to access the needed variable as a property of the containing object.
If defined in the global scope using var
, in javascript the value is assigned as a property of the global object, and it can be accessed using the self explanatory keyword globalThis
In JavaScript, there's always a global object defined. In a web browser, when scripts create global variables defined with the var keyword, they're created as members of the global object. (In Node.js this is not the case.)
var subcatlist1 = 'aa';
var subcatlist2 = 'bb';
var subcatlist3 = 'cc';
var itemNumber = parseInt(Math.random() * 3) + 1
$('#test').html(globalThis['subcatlist' + itemNumber])
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
See also "Variable" variables in JavaScript
Original answer
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 in most cases
Upvotes: 0
Reputation: 15393
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]);
Upvotes: 2