3

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();
}
Dev
  • 181
  • 12

3 Answers3

1
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?

Community
  • 1
  • 1
evilReiko
  • 19,501
  • 24
  • 86
  • 102
0

use window['answeredQ'+i] but you are probably better assigning the answer to an array, rather than directly to the global scope.

var count = 5;
for (var i = 0; i < count; i++) {
  var className = '.myclass' + i;
  window['answeredQ' + i] = $(className).map(function() {
    return $(this).text();
  }).get();
}
synthet1c
  • 6,152
  • 2
  • 24
  • 39
0

As this variable declaration is invalid, you can use an object to hold all this dynamic keys and use the same outside the for loop as below.

var count = 5;
var answers = {};

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

console.log(answers);

Object.keys(answers).forEach(function(key) {
  console.log(key + ': ');
  console.log(answers[key]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Aruna
  • 11,959
  • 3
  • 28
  • 42