简体   繁体   English

javascript变量和值的串联

[英]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 . 我想做的是将选项选项中给定变量的值插入到元素中,但是变量的“数字”(即1、2或3)本身作为变量进入,例如itemNumber

What I would like to do is: $(element).html(subcatlist+ itemNumber); 我想做的是:$(element).html(subcatlist + itemNumber);

... Which would give the value of aa for itemNumber = 1 ...这将为itemNumber = 1给出aa的值

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. 我得到的错误是: ReferenceError: subcatlist is not defined这很有意义,因为变量subcatlist不存在-仅存在subcatlist1subcatlist2subcatlist3

Do how can i concatenate the subcatlist + itemNumber to get a variable that i can use, as subcatlist1 etc? 我该如何将subcatlist + itemNumber连接itemNumber以获取一个我可以使用的变量,例如subcatlist1等?

Thanks 谢谢

Use object instead of variable is better approach in your context,Because you concadenate with variable is wrong. 在您的上下文中使用object而不是variable是更好的方法,因为与变量一起使用是错误的。

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: 如果必须包含变量列表,则可以使用eval(),如下所示:

$(element).html(eval("subcatlist"+ itemNumber)); $(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 评估可能是有害的,在处理用户输入时应避免使用评估,如果可能的话,我会使用Sudharsan提出的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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