0

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!

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.