0

I am trying to create dynamic variable, for example rather saying

let f0, f1 = '';

and then using these variable in forEach

{Object.keys(shop).forEach((element, key) => {
              if (element == dName[0]) {
                f0 = Object.values(shop)[key];
              }           
              if (element == dName[1]) {
                f1 = Object.values(shop)[key];
              }
            })}
        

trying below,

let k = 'f'; 
    let i = 0; 
    for(i = 1; i < 2; i++) { 
        eval('let ' + k + i + '= \'\' ;'); 
    } 
    console.log("f1=" + f1); 

but console printing

f1=undefined

what wrong I am doing, thanks in advance
2
  • 6
    Why would you do this? It negatively affects security, performance, readability, maintainability, and you don't need it. If you want dynamic identifiers, use an object with computed property names Commented Aug 15, 2020 at 19:46
  • Just don't do that, please. Don't use eval Commented Aug 15, 2020 at 19:47

1 Answer 1

4

i don't know if it is possible with eval but you could use an object to store your variables like this

let k = 'f'
let vars = {}

for(i = 1; i < 5; i++) { 
  vars[k+i] = '' 
} 
console.log(vars)
console.log("f1=" + vars.f1); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.