Home How i can use looping to declare dynamic variable in JavaScript?
Reply: 3

How i can use looping to declare dynamic variable in JavaScript?

Eslam Bakr
1#
Eslam Bakr Published in 2017-09-11 11:41:42Z

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 */
}

connexo
2#
connexo Reply to 2017-09-11 12:20:29Z

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);
}
Danil Speransky
3#
Danil Speransky Reply to 2017-09-11 11:43:51Z

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])
Debabrata
4#
Debabrata Reply to 2017-09-11 11:44:44Z

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]

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.296207 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO