I have multiple variables named for instance "s11" and "s12" etc.
var s11 = 0;
var s12 = 0;
In addition to that, I also have an array containing all the names of these variables.
var wA = new Array("s11", "s12");
The values in the array are added automatically in the script later on, depending on user activity.
My problem is that I would like for example the variable "s11" to ++ every time it occurs as a value in the array. Can this be done?
5 Answers 5
Using variables, will make your life hard. Here is one approach that does both. Use associative array, like this:
var count = {};
var wA = new Array("s11", "s12");
function updateArray(value) {
wA.push(value);
if(! (value in count) ) {
count[value] = 0;
}
count[value]++;
}
Then use it like:
updateArray("s11");
updateArray("s12");
Now count will look like: {s11: 1, s12: 1} & wA will look like: ['s11', 's12']
3 Comments
You could use the eval() function. It runs any code given as argument. For example, to ++ each variable when its name appears in the array, use:
for(variablename in wA){ // or any other way to loop through the array
eval(variablename + "++");
}
Also, you could use the owner object like an associative array. If the variables are global, just use window.
for(variablename in wA){ // or any other way to loop through the array
window[variablename]++;
}
Comments
If your s variables are global then you could dot he following :
for (var i = wA.length; i--;)
window[wA[i]] ++;
Comments
If they are global variables, you can grab them from the window object using bracket notation:
window[wA[0]]; // 0
Otherwsie, I would recommend using an object instead of variables:
var myVars = {
s11 : 0,
s12 : 0
};
myVars[wA[0]]; // 0
The only other way is using eval, which might be dangerous if you're dealing with user input.
Comments
If your variables are global you can do as shown below
s11 = 10;
s12 = 12;
var i = 11;
var wA = new Array(window["s" + i++], window["s" + i]);
Otherwise you will have to declare the variables in a scope , for e.g: using this
this.s11 = 10;
this.s12 = 12;
var i = 11;
var wA = new Array(this["s" + i++], this["s" + i]);
Or you can use a loop to push elements
var wA = [];
for(var i=11; i<=12; i++){
wA.push(this["s" + i]);
}
NOTE: starting and end values of i depends on your requirement and implementation
var fields = {"s11":0,"s12":0};