Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add counter variable to variable name?

Tags:

javascript

Pretty straightforward. 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'm sure this can be made way more efficiently, It should go up to "#survey13" but I skipped the rest to save space. Maybe a for loop? How could I add the counter to the name of the variable and referenced id?

like image 942
TianRB Avatar asked Sep 22 '15 04:09

TianRB


2 Answers

You can say like bellow

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

So actually your slider1 is sliders[0] and slider2 is sliders[1] and so on.

like image 56
Mritunjay Avatar answered Sep 26 '22 07:09

Mritunjay


You can use for loop to create a slider with the each item. You can add the slider instance in 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 support multiple selectors

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

Another way would be assigning a common class to all the elements and using this class to assign slider. As said above, this depends on the definition of Slider.

var slider = new Slider(".slider", {
    precision: 2,
    value: 5
});
like image 23
Tushar Avatar answered Sep 23 '22 07:09

Tushar