Hate Names
Hate Names

Reputation: 1606

Is it possible to reference a variable

I have an object with about 30 'values' or whatever they are called, for example:

var list = new Object();
list.one = 0;
list.two = 0;
list.three = 0;
...
list.thirty = 0;

Is there a simple/efficient way for me to be able to increment the values of the list object?

For example let's say there are 100 buttons, each button if pressed will increase the value by a certain amount. What I'm trying to do is a short function like:

function test( value, amount, math ) {
   if( math === "add" ) {
   value += amount;
   } else if( math === "sub" ) {
   value -= amount;
   }
}

However, the whole value thing doesn't work. The only other way I can think about doing it is creating 30 functions, each function to do the same thing as above but each one specifies the list value to add or subtract to, or make a single function with if value === "one" then list.one etc. Any other ideas? I've thought about using an array but I'd prefer having the code be easy to read since the list values have specific names that make it easy for me in other functions.

Upvotes: 0

Views: 109

Answers (4)

Jackson Ray Hamilton
Jackson Ray Hamilton

Reputation: 9466

list[value] += amount;

Where value is a string like "one", "two", etc.

You could also pass in the object to increment:

function(obj, value, amount, math) {
  obj[value] += math;
}

But you should probably use an array + a loop / refactor.

Upvotes: 1

Bergi
Bergi

Reputation: 664650

Is it possible to reference a variable?

No. But it is possible to reference an object, and use variable property names. That's actually what you already have, so you could change your function to

function test( value, amount, math ) {
    if( math === "add" ) {
        list[value] += amount;
    } else if( math === "sub" ) {
        list[value] -= amount;
    }
}

and call it with test("one", 100, "add") instead of test(list.one, 100, "add"). Btw, I'd recommend to just use negative values instead of add/sub verbs.

Upvotes: 1

Guffa
Guffa

Reputation: 700432

You can access the properties by name as a string:

function test(obj, name, amount, math) {
  switch (math) {
    case "add":
      obj[name] += amount;
      break;
    case "sub":
      obj[name] -= amount;
      break;
  }
}

Call it using for example:

test(list, "one", 1, "add");

Upvotes: 1

Samuel Reid
Samuel Reid

Reputation: 1756

Try something like this:

function inc(value,amount) {
  list[value] += amount;
}

Upvotes: 5

Related Questions