通过函数参数确定变量

时间:2016-12-05 18:55:28

标签: javascript function

我想知道你是否可以"结合"变量和函数参数?如果是这样,你怎么能这样做?

E.g。

var word1 = 1;
var word2 = 13;
var word3 = 3;

function magicFunction (magicParameter) {
  //something magical happens here
  return magicVariable; //"word" + magicParameter somehow
}

magicFunction(1) = 5; //word1 = 5
magicFunction(2) = 13; //word2 = 13
magicFunction(3) = 3; //word3 = 3

谢谢!

更新:您可以使用eval()执行此操作:



var word1 = 5;
var word2 = 13;
var word3 = 3;

function magicFunction (magicParameter) {
  var magicVariable = eval("word" + magicParameter);
  return magicVariable; //"word" + magicParameter somehow
}

console.log( magicFunction(1) ) //word1 = 5
console.log( magicFunction(2) ) //word2 = 13
console.log( magicFunction(3) ) //word3 = 3




1 个答案:

答案 0 :(得分:-1)

这里的魔法值是+

var word1 = 1;

function combine (index) {
  magicVariable = word1 + index;
  
  return magicVariable;
}

console.log(combine(1));