简体   繁体   中英

How I could use template literals in javascript in a variable name?

I want to declare a variable name via template literals How it is possible?

 let z = 3; let test`${z}` = "hello"; //or = new obj() for example console.log(test3);

Reference: Template literals

It is not possible. Template literals are used for strings only.

It is same as: var 'string_var' = 'myval' // Not accepted.

But, you can do it for object properties.

Such as:

 let z = 3; let obj = {} obj[`test${z}`] = "hello" console.log(obj.test3);

Yes, is possible. This is my code, referencing: Can you use template literal for function name in javascript?

 for (i = 1; i < 10; i++) { global[`list_${i}`] = require(`./LP_${i}_Top_Holder.json`); }

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