0

I render the for loop using variable count. Please check this example

I have 5 variable like this:

var reactionWeightage5 = 30;
var reactionWeightage4 = 06;
var reactionWeightage3 = 70;
var reactionWeightage2 = 80;
var reactionWeightage1 = 10;

i need render like this

for (var i = 1; i <= 5; i++) {
    var test = reactionWeightage[i];
    etc .....
}

i am getting the following error :

"reactionWeightage is not defined"

Can anyone help for this?

2
  • 1
    Why do you have 5 separate variables instead of an array with 5 entries? Commented Jan 3, 2014 at 14:44
  • 1
    If you really want to (I'd go for the Array option though) you could do something like this['reactionWeightage' + i] Commented Jan 3, 2014 at 14:49

4 Answers 4

3

Simplest way is to just create the array like so:

var reactionWeightage = [30, 06, 70, 80, 10];

Iterate

for (var i = 0; i < reactionWeightage.length; i++) {
     console.log(reactionWeightage[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

reactionWeight is not an array. You need to use arrays if you use the [] operator.

Try creating something like this:

var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

then you can access it like this:

alert(mycars[2]); //will alert BMW

http://www.w3schools.com/js/js_obj_array.asp

Comments

1

Instead of using five variables, use for example a dictionary/object:

var reactionWeightage = {
    5: 30,
    4: 06,
    3: 70,
    2: 80,
    1: 10
};

for (var i = 1; i <= 5; i++) {
    var test = reactionWeightage[i];
    etc .....
}

However to answer the question completely here's an example how to achieve what you want (only for academic purposes, do not use it in real code):

for (var i = 1; i <= 5; i++) {
    var test = eval('reactionWeightage'+i);
    etc .....
}

3 Comments

dictionary? are you ok?
@Trickster: It's a valid term :-)
@Trickster - are you ok?
0

You need to define reactionWeightage as an array, not declare 5 separate variables. Minimally fixing what you've got already:

var reactionWeightage = new Array();
reactionWeightage[5] = 30;
reactionWeightage[4] = 06;
reactionWeightage[3] = 70;
reactionWeightage[2] = 80;
reactionWeightage[1] = 10;

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.