简体   繁体   English

JavaScript:使用函数参数定义变量名称

[英]JavaScript: Define variable name with function parameter

Is it possible in JavaScript to define a variable name with a function parameter? 在JavaScript中是否可以使用函数参数定义变量名称?

Here is my jsFiddle . 这是我的jsFiddle In the example below, I would like varB to be defined as null when it is passed through makeNull(varName) : 在下面的示例中,我希望varB在通过makeNull(varName)传递时定义为null

var varA = undefined;
if (varA == undefined) {
  varA = null;
}
var varB = undefined;

makeNull(varB);

function makeNull(varName) {
  if (varName == undefined) {
    varName = null;   
  }
}  

alert (varA + ' | ' + varB);

如果您尝试使用函数参数定义变量,那么您要么使用数组或对象。

JavaScript doesn't provide "call by reference" parameters. JavaScript不提供“按引用调用”参数。 When you call a function, it receives the values of the argument expressions, not references to the variables that were in the expressions. 调用函数时,它接收参数表达式的值,而不是对表达式中变量的引用。 So it can't modify the bindings of those variables. 所以它不能修改那些变量的绑定。

If you want to do something like this, you can use containers and labels, eg 如果你想做这样的事情,你可以使用容器和标签,例如

function makeNull(obj, label) {
  if (obj[label] === undefined) {
      obj[label] = null;
  }
}
var varB = { abc: undefined }
makeNull(varB, 'abc');

you can pass a variable (defined as 'undefined') to a function and set its value. 您可以将变量(定义为'undefined')传递给函数并设置其值。

http://jsfiddle.net/AwnVN/ http://jsfiddle.net/AwnVN/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM