I have 4 variables containing 4 different strings. I want to use a for-loop for the creating of a table, and apply the strings into the cells. With my code below i get “content1”, “content2” and so on as strings, instead of the strings in the variables content1, content2 and so on. Is it possible to convert the strings that are created in the loop (eg. “content1”) to the variables, if so how do I do?
var content1 = "Text1";
var content2 = "Text2";
var content3 = "Text3";
var content4 = "Text4";
for (var i = 1; i < 5; i++){
var td = document.createElement('td');
var text = document.createTextNode("content" + [k]);
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
Try
window['content' + k]instead, but also seriously consider changing your design so you DON’T need variable variables. They’re a horrible monstrosity and lead to next-to-impossible-to-debug code.At bare minimum, switch to using an array: