0

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;
   }
}

but the whole value thing doesnt 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.

Thanks in advance for any help

Hate Names
  • 1,596
  • 1
  • 13
  • 20
  • 1
    `var list = new Object();` so it's not a list...anyway, are you aware of arrays in javascript? – gdoron Jul 31 '13 at 18:55
  • I think using an array is the best solution for you.Never ever do the computer's job (to write manually from list.one to list.thirty ) – Ionel Lupu Jul 31 '13 at 18:58
  • Your function did not work because value was resolved to a value. Though not perfectly correct, Javascript more-or-less passes Arrays and Object by reference, but numbers and strings by value. – Paul Jul 31 '13 at 18:59

4 Answers4

5

Try something like this:

function inc(value,amount) {
  list[value] += amount;
}
Samuel Reid
  • 1,756
  • 12
  • 22
1

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");
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1
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.

Jackson
  • 9,188
  • 6
  • 52
  • 77