Dev
Dev

Reputation: 181

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();
}

Upvotes: 3

Views: 358

Answers (3)

evilReiko
evilReiko

Reputation: 20473

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?

Upvotes: 1

Aruna
Aruna

Reputation: 12022

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>

Upvotes: 0

synthet1c
synthet1c

Reputation: 6282

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();
}

Upvotes: 0

Related Questions