简体   繁体   中英

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? 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.

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['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.

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