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();
}
6
  • use eval ...... Commented Nov 30, 2016 at 7:16
  • Then how To use it? Commented Nov 30, 2016 at 7:17
  • w3schools.com/jsref/jsref_eval.asp Commented Nov 30, 2016 at 7:18
  • What you intent to use with the variable? Commented Nov 30, 2016 at 7:19
  • @Dev Why do you need a variable with the name answeredQ1, answeredQ2, ... ? Commented Nov 30, 2016 at 7:20

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

This window['answeredQ'+i] will create the variable in global scope, right?
Yes, as said it's not ideal.
how to use this window['answeredQ'+i] outside for loop?
it's the same as any variable declared in the global scope (outside of a function) answeredQ0 or window.answeredQ0 or window['answeredQ0']
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.