简体   繁体   中英

JavaScript: Define variable name with function parameter

Is it possible in JavaScript to define a variable name with a function parameter?

Here is my jsFiddle . In the example below, I would like varB to be defined as null when it is passed through makeNull(varName) :

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. 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.

http://jsfiddle.net/AwnVN/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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