How to add a counter variable to a variable name?

Pretty simple. This is my very inefficient code:

var slider1 = new Slider("#survey1", { precision: 2, value: 5 }) var slider2 = new Slider("#survey2", { precision: 2, value: 5 }) var slider3 = new Slider("#survey3", { precision: 2, value: 5 }) var slider4 = new Slider("#survey4", { precision: 2, value: 5 }) var slider5 = new Slider("#survey5", { precision: 2, value: 5 }) 

I am sure that this can be done more efficiently, it should go to "# survey13", but I skipped the rest to save space. Maybe a for loop? How can I add a counter to a variable name and reference identifier?

+5
source share
5 answers

You can say as below

 var sliders = [] for (var i = 1; i <= 13; i++) { var slider = new Slider("#survey" + i, { precision: 2, value: 5 }); sliders.push(slider); } 

So, your slider1 is equal to sliders[0] and slider2 is equal to sliders[1] , etc.

+9
source

You can use the for loop to create a slider with each element. You can add a slider instance to the array and use it later.

 var options = { precision: 2, value: 5 }; var slider = []; for (var i = 1; i <= 13; i++) { slider.push(new Slider("#survey" + i, options)); } 

If the plugin supports multiple selectors

 var slider = new Slider("#survey1, #survey2, #survey3 ...", { precision: 2, value: 5 }); 

Another way is to assign a common class to all elements and use this class to assign a slider. As stated above, it depends on the definition of Slider .

 var slider = new Slider(".slider", { precision: 2, value: 5 }); 
+4
source

Try with an array:

 var sliders = []; var cfg = { precision: 2, value: 5 }; for (var i = 1; 13 >= i; i++) sliders[i] = new Slider("#survey" + i, cfg); 

If you want to have named variables, go for the object:

 var sliders = {}; var cfg = { precision: 2, value: 5 }; for (var i = 1; 13 >= i; i++) sliders['survey' + i] = new Slider("#survey" + i, cfg); 
+2
source

Better than an array, as others have suggested, to use an object:

 var id = 'survey', sliders = {}, i = 13; do { sliders[id + i] = new Slider('#' + id + i, { precision: 2, value: 5 }); } while(i--); 

Then you can use the created object: sliders.survey1 , sliders.survey2 , etc.

+1
source

you cannot change the reference id, but you can create it with php to the download page

 <?php $i=0; for($i;$i<n;$i++) { echo 'var slider = new Slider("#survey'+$i+'", { precision: 2, value: 5 })';} ?> 
0
source

Source: https://habr.com/ru/post/1231983/


All Articles