0

I am having problem to figure correct syntax to make those Javascript dynamic variable works:

I want to replace this code:

<code>
    var res1 = res0.replace('[a1]', a1);
    var res2 = res1.replace('[a2]', a2);
    (...)
    var res7 = res6.replace('[a7]', a7);
</code>

With something dynamic, like

<code>
for (var i = 1; i < 8; i++) {
    **var str2 ="res" + i + " = res + i + .replace('[a + 'i']', window['a' + i])";**
    eval(str2);
}
</code>

The ElementID is recovered from another Dynamic Variable, that works

<code>
    for (var i = 1; i < 8; i++) {
        var str ="a" + i + " = document.getElementById('a'+i).value";
        eval(str);
    }
</code>

General idea is simple. Capture from a form, (input type text) and replace the strings called [a1], [a2], etc inside a textarea. Code works without dynamic variables.

Any idea is more than welcome.

Thank you

3
  • 1
    What is res0? You probably don't need all these dynamic code. You could solve it using an array. Commented Sep 15, 2020 at 18:13
  • eval()... out in the wild... what am I SEEING?!?!?!?!?!!?!?!?!!?!?!?!?!?!?!? what is this madness!? Commented Sep 15, 2020 at 18:17
  • You could do something like this: jsfiddle.net/adigas/nzm7a8ht Commented Sep 15, 2020 at 18:58

1 Answer 1

1

so don't use eval... bad practice, much bugs, little security, unexpected results...

it sounds like you just need an array.

(if you are using a for loop and eval - chances are you really want an array instead). here is code that does not use eval()

reses = [] // of res0, res1 etc
for (let i = 1; i < 8; i++) {
    reses[i].replace(`[a${i}]`, window[`a${i}`]);
}
    for (let i = 1; i < 8; i++) {
        let element =document.getElementById(`a${i}`).value;
    }
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.