0

Is there a way to include variables in each iteration of a javascript loop? For example if I put this code into a loop

if (e1) {item_text += '{id:"' + id[1] + '",lvl:' + e1lvl + '},<wbr>'} 
if (e2) {item_text += '{id:"' + id[2] + '",lvl:' + e2lvl + '},<wbr>'} // etc

and do something like

for (n = 0; n < id.length; n++) { 
  if (e/*concat var e w/var n?*/) { 
    item_text += '{id:"' + id[1] + '",lvl:' + e/*concat var e w/var n?*/lvl + '},<wbr>'
  }
}

Is there a way to change the number in the var names (e1 -> e2 etc) each iteration or do i just have to keep it the long way and write everything out on its own line?

1
  • 2
    This seems like an X/Y issue. Can you post what you're trying to accomplish? There's most likely an easier way. Commented Jul 28, 2018 at 21:34

3 Answers 3

2

It would be possible, though highly not recommended, to use eval to come up with the variable name:

const e1lvl1 = 'foo';
const e2lvl1 = 'bar';
for (let i = 1; i < 3; i++) {
  console.log(eval('e' + i + 'lvl1'));
}

But it would be better to fix your script's architecture so that this isn't necessary: put each e#lvl into an array, and then access the appropriate index of the array on each iteration:

const elvl = [
  'foo',
  'bar'
];
let item_text = '';
for (let i = 0; i < elvl.length; i++) {
  item_text += 'lvl: ' + elvl[i] + '\n';
}
console.log(item_text);

Sign up to request clarification or add additional context in comments.

1 Comment

Avoid eval() like the plague. If you're using it, you're likely writing the code in a bad manner that can be refactored without it.
1

Arrays/Objects exist in javascript for a reason! Simplify your code. There is no reason to have e1, e1l, e2... as variables. Add them to an object and access them by key, or add them to an array, and loop through them. There are many javascript functions as well that will allow you to ensure all elements match a certain condition.

function submit() {
    var e = {};
    var idx = 28;
    
    for (var i = 0; i <= 24; i++) {
      e[i] = {};
      e[i].key = document.getElementById(`ench${i}`).checked
      e[i].value = $.trim(form.elements[idx].value)
      
      idx += 2;
    }
    
    // Check condition
    if (Object.values(e).some(e => e.key)) {
      //One of the checked items was true
    }
    
}

Comments

0

I would agree that you should change your code to use arrays.

To answer your question though, since your e1 and e1lvl variables look to be global scope, you can access them like this

window["e1"]
window["e1lvl"]

Give this a try

for (n = 0; n < id.length; n++) { 
  if (window["e" + n]) { 
    item_text += '{id:"' + id[n] + '",lvl:' + window["e" + n + "lvl"] + '},<wbr>';
  }
}

2 Comments

It can't be concluded from the code posted that they're global. They may very well be function-scoped. (in fact, if you look at the link he posted, you'll see that that's exactly the case - they're not global, they're in a function)
@CertainPerformance good catch, I didn't notice that comment. That should be in the body of the question.

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.