Reputation: 1892
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?
Upvotes: 0
Views: 71
Reputation: 56467
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 .....
}
Upvotes: 1
Reputation: 2432
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;
Upvotes: 0
Reputation: 104775
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]);
}
Upvotes: 3
Reputation: 5963
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
Upvotes: 1