简体   繁体   English

串联名称变量(非值)Js

[英]Concatenate name variable (not value) Js

My problem is simple: 我的问题很简单:

I want to concatenate a dynamic variable name in a function, so with the name insert in parameter, when I call the function, she concat automatically the string in the new variable name. 我想在一个函数中连接一个动态变量名,因此使用在参数中插入名称的方法,当我调用该函数时,她会自动在新变量名中连接字符串。

Exemple (wrong, I think): 例子(我认为是错误的):

function blockDL(insertName){

    return var 'block' + insertName + 'DT'= document.createElement('dt');  

};

blockDL('First'); 

I expect the code return: 我希望代码返回:

blockFirstDT = document.createElement('dt');

Thanks for your help ! 谢谢你的帮助 ! =) =)

What you want is not possible. 您想要的是不可能的。 See "Variable" variables in Javascript? 参见JavaScript中的“变量”变量吗? for alternatives of what you can do. 替代您可以做的事情。

However, "variable variables" is usually a indicator of bad code design. 但是,“变量变量”通常是不良代码设计的指标。 Especially in your case, there is absolutely no reason or benefit to do any of these. 尤其是在您的情况下,绝对没有理由或这样做的好处。 Just name the variables blockDT and paraphDT or whatever you want. 只需命名变量blockDTparaphDT或任何您想要的名称即可。

The only way you will be able to use a string for a variable name is by placing it as the property of another object. 您可以将字符串用作变量名的唯一方法是将其放置为另一个对象的属性。 if you want the variable global you could use the window object. 如果要全局变量,则可以使用window对象。

window['block' + insertName + 'DT'] = document.createElement('dt');

that said, you really shouldn't need to and should probably look for other ways of structuring your code. 就是说,您确实不需要,可能应该寻找其他方式来构造代码。

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

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