1

i have a lot of variables in JavaScript maybe 50 variables, and i want to declare variables by using loop, how i can do it dynamically.

var img1,img2,img3;
for(var i =1; i<50; i++){
  var img+i = document.getElementById(i);
  /* i wanna doing some thing like that */
}

2
  • 3
    is it ok to put them in an object or array? obj["img" + i] = document.getElementById(i); Commented Sep 11, 2017 at 11:43
  • 2
    What you're looking for is called an "array". Commented Sep 11, 2017 at 11:44

3 Answers 3

2

Consider storing variables in an object:

var images = {}

for (var i = 1; i < 50; i++) {
  images['img' + i] = document.getElementById(i)
}

// usage
console.log(images.img5)

Or in an array:

var images = []

for (var i = 1; i < 50; i++) {
  images.push(document.getElementById(i))
}

// usage   
console.log(images[4])
Sign up to request clarification or add additional context in comments.

1 Comment

Actually i do it, but i don't have enough reputation.
0

This will create variables img1 ... img49 on the global object (in the global namespace):

for(var i = 1; i < 50; i++){
  window['img'+i] = document.getElementById(i);
}

Comments

0

you can create a javascript array. e.g--

var array=[];
for(var i =1; i<50; i++){
    array[i] = document.getElementById(i);
}

after that you can call that element by array[i]

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.