0

Creating static variables is not an option in this case becouse it would take to long time and ineffective to what im trying to accomplish. I have an Array with images and I'm trying to create a way to make divs according to the length of the array. 1,2,3,4 etc.

var images = ['image1.JPG', 'image2.JPG', 'image3.JPG'];
var totalimages = images.length;

Which will result in an array length of 3. I would like to create 3 variables for this.

for (var i = 0; i > totalimages; i++){
  var div[i] = document.createElement('div');

}

This seems not to be working for some reason. I tried to create a div array/list outside the for loop aswell.

var div = [];

for (var i = 0; i > totalimages; i++){
  var div[i] = document.createElement('div');

}

Still not working. I dunno why this is not working. Javascript only

EDIT: (not working) i mean it gives me syntax error.

4
  • define 'not working'. Commented Aug 29, 2014 at 13:17
  • Remove the var inside the loop. Commented Aug 29, 2014 at 13:19
  • Have you actually created an object called div? Commented Aug 29, 2014 at 13:20
  • var inside the loop was the problem. Commented Aug 29, 2014 at 13:22

3 Answers 3

2

You have defined div already. In loop you shouldn't be saying like var div again.

BTW var div[ will cause a syntax error.

Use this

div[i] = document.createElement('div');

instead of

var div[i] = document.createElement('div');

Any way I'll prefer saying this at that place

div.push(document.createElement('div'));

And this will cause i > totalimages an infinitive loop, say i < totalimages instead.

Sign up to request clarification or add additional context in comments.

1 Comment

To clarify, the problem is not that he variable is already declared, var div[ is simply invalid syntax.
1
i < totalimages

not

i > totalimages

Make sure you don't use var inside the array if you're assigning new values:

var div = [];
for (var i = 0; i < totalimages; i++){
  div[i] = document.createElement('div');
}

DEMO

1 Comment

Yeah, but it still dosent slove my problem with dynamic variables.
0

In short:

var images = ['image1.JPG', 'image2.JPG', 'image3.JPG'];
var totalimages = images.length;
var div = [];

for (var i = 0; i < totalimages; i++){
  div.push(document.createElement('div'));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.