minute acc
minute acc

Reputation: 11

Variable from parameter in Function

Maybe I'm missing something so sorry if that's the case but does anyone know if it's possible in jQuery to use the parameter from a function in a variable. For example:

function number(x){
  variable_number_x++;
}

And in that code replace x with the function parameter. So for example number(2) would output that it adds 1 to the variable_number_2 variable. Any idea's? Thanks in advance!

Upvotes: 0

Views: 84

Answers (1)

user1726343
user1726343

Reputation:

window["variable_number_"+x]++; is probably what you need.

I am assuming here that variable_number_2 is a global, but you can replace window with whatever object variable_number_2 is a property of. Alternatively, you can specify an optional parameter that takes the object that the variable is a property of:

var obj = {variable_number_2: 5};
function number(x,obj){
  if(typeof(obj)=="undefined"){
      obj = window;
  }
  return ++obj["variable_number_"+x];
}
console.log(number(2,obj));                 //logs 6
console.log(obj.variable_number_2); //logs 6

Upvotes: 1

Related Questions