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

Answers


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

Need Your Help

Event Hub Lease Management

azure azure-eventhub

Does anyone know where I can find details about how event hub lease management works? Specifically I'm trying to find how do I know where in the event hub the EventProcess picks up processing (aft...

Measuring Human-Flatulence Propagating Wave Packet on the iPhone

iphone objective-c waveform envelope

Using my iPhone, I would like to measure human flatulence in order to measure, quantify, and provide a statistical report based on various properties of the overall event quality. Outrageous, maybe.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.