0

如果是这种情况,也许我错过了一些非常抱歉的东西,但有谁知道在 jQuery 中是否可以使用变量中函数的参数。例如:

function number(x){
  variable_number_x++;
}

并在该代码中将 x 替换为函数参数。因此,例如 number(2) 将输出它将 1 添加到 variable_number_2 变量。有任何想法吗?提前致谢!

4

1 回答 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
于 2012-11-05T20:00:11.757 回答