Maneesh M S
Maneesh M S

Reputation: 367

Update javascript variable using another variable value

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

Answers (5)

Adrian Salazar
Adrian Salazar

Reputation: 5319

Let's see the facts here:

  • Your variables have a pattern: variable_x so, for our algorithm it s just a string: 'variable_' + x
  • All your variables will be attached to an object, wetter it is a declared object, or a global one, for example: a, myVars, or window
  • Any object in javascript can be accessed using indexers, so myObject.myVar can be also written like myObject['myVar'].

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

Sergio
Sergio

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

Alexey Odintsov
Alexey Odintsov

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

basilikum
basilikum

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

Jacob
Jacob

Reputation: 4021

function update_varable(variable){
   variable += 10;

return variable;
}

Upvotes: -1

Related Questions