Reputation: 367
I have a situation as follows.
var varable_1=10;
var variable_2=20;
.....
var variable_n=10000;
function update_varable(variable){
....some code.....
}
I need to update each of those variables by calling update_variable('variable_1');update_variable('variable_2')....etc.
Is it possible?
Upvotes: 1
Views: 94
Reputation: 5319
Let's see the facts here:
Now let's see the algorithm:
function update(variable, value){
window[variable] = value;
}
You can call it like you wanted:
update('variable_1', 450.25);
Upvotes: 1
Reputation: 28837
If you want to pass the variables inside the function update_variable
then you need to remove the quotes in your example. There is many ways to do it, I post a simple one. You can also pass more than one variable inside the function.
Demo here
var varable_1=10;
var variable_2=20;
var variable_n=10000;
function update_variable(x){
x = 300 //some new value
return x;
}
and the call:
variable_1 = update_variable(varable_1);
( your function name misses an "i" on some lines, it's "update_varable" )
^
missing "i"
Upvotes: 2
Reputation: 1715
I think array is more suitable for the task.
But you can use this code with eval function if your varaibles names are like var1, var2 .. varN:
var var1 = 10;
var var2 = 20;
function update_var(variable) {
return variable += 1;
}
function main() {
for (var i = 1; i < 3; i++) {
eval("var" + i + " = update_var(var" + i + ")");
eval("console.log(var" + i + ");");
}
}
Upvotes: 1
Reputation: 10528
If you have to use a string as argument for the update function, you can use eval
inside of the function to get the real variable behind the string:
function update(varName) {
eval(varName + " += 1;");
}
Upvotes: 1
Reputation: 4021
function update_varable(variable){
variable += 10;
return variable;
}
Upvotes: -1