Felipe Pasetto
Felipe Pasetto

Reputation: 25

Javascript - Dynamic variable

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

Upvotes: 0

Views: 49

Answers (1)

altruios
altruios

Reputation: 1083

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;
    }

Upvotes: 1

Related Questions