holyredbeard
holyredbeard

Reputation: 21218

Convert string to variable, possible?

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

Upvotes: 1

Views: 2289

Answers (5)

FailedDev
FailedDev

Reputation: 26930

Since this is homework here is some food for though:

Put all your variables in a "content" array :

var content = new Array("Text1", "Text2" ...);

Then iterate through it and access it like content[i]

for (var i = 0; i < content .length; i++){...}

Hope it helps :)

Upvotes: 0

u.k
u.k

Reputation: 3091

For this specific case, you could use and array to hold your strings:

var content = ['Text1', 'Text2', 'Text3', 'Text4'];

And later

var text = document.createTextNode(content[i+1]);

Another very not recommended option is to evaluate the code:

eval("var text = content" + (i+1));
var text = document.createTextNode(text);

This will work but has risks, and is flaky in general.

Upvotes: 1

Robert
Robert

Reputation: 3074

Creating content as an array should work.

var content = new Array();

content[0] = "Text1";
content[1] = "Text2";
content[2] = "Text3";

for (var i = 1; i < 5; i++){        
    var td = document.createElement('td');
    var text = document.createTextNode("content" + content[k]);
    td.appendChild(text);
    tr.appendChild(td);
}

table.appendChild(tr);

Upvotes: 0

Mike Christensen
Mike Christensen

Reputation: 91618

Yes.

var content = ["Text1", "Text2", "Text3", "Text4"];

for (var i = 0; i < content.length; i++){        
    var td = document.createElement('td');
    var text = document.createTextNode( content[i] );
    td.appendChild(text);
    tr.appendChild(td);
}

table.appendChild(tr);

Upvotes: 1

Marc B
Marc B

Reputation: 360682

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:

content = ['', 'Text1', 'Text2', 'Text3', 'Text4']; // empty string to fill in the '0' element

alert(content[1]); // outputs Text1

Upvotes: 3

Related Questions