user2894386
user2894386

Reputation: 69

Multiple variables on one line with same behind =

I'm working with JavaScript since 2 weeks and I wanted to make something easier if it were possible.

I got this in my JS:

var div0 = document.createElement("div");
var div1 = document.createElement("div");
var div2 = document.createElement("div");
var div3 = document.createElement("div");
var div4 = document.createElement("div");
var div5 = document.createElement("div");
var div6 = document.createElement("div");
var div7 = document.createElement("div");

Is there a way to get this all on one line? (Not having to retype the whole thing everytime?) Everything in the line is the same exept for the number behind div.. Isn't the way I do it just a waste of space?

Thanks!

Upvotes: 0

Views: 79

Answers (2)

MC ND
MC ND

Reputation: 70923

This "should" not be done, but the only way i know, with the limitations initialy imposed, to get the same result, 8 variables defined and each referencing a new created div is

for ( var i=0; i<8; i++ ) eval('var div'+i+'=document.createElement("div");');

Upvotes: 0

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

var divs = [];
for (var i = 0; i < 8; i++ ) {
    divs.push(document.createElement("div"));
}

Now each array element inside divs will contain different div element.

Upvotes: 3

Related Questions