Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Variable Declaration

Every thing goes fine but when i declaring Variable answeredQ+i Getting Error

var count = 5;
for(var i=0;i<count;i++){
    var className = '.myclass'+i;
    var answeredQ+i = $(className).map(function(){
        return $(this).text();
    }).get();
}
like image 332
Dev Avatar asked Apr 15 '26 06:04

Dev


1 Answers

var count = 5;
var answered = {};
for(var i=0;i<count;i++){
    var className = '.myclass'+i;
    answered['Q' + i] = $(className).map(function(){
        return $(this).text();
    }).get();
}

Now you can use answered.Q1 or answered['Q1'] to access first variable, Q2 for 2nd variable, etc.

What you're trying to achieve is known as 'Variable variable'. Many programming languages supports it, but in Javascript there is no straightforward answer, so you have to use an array or object to contain the new variables.

Read about 'variable variable' for more details: "Variable" variables in Javascript?

like image 187
evilReiko Avatar answered Apr 16 '26 19:04

evilReiko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!