简体   繁体   中英

Get the name of the input variable in a function

This appears to be a difficult question to answer. Given a function such as the one displayed how would you get the name of the input variable for debugging purposes. ie) root -> root.left -> root.right -> root.left.right -> etc... or ie) tree -> tree.left -> tree.right -> tree.left.right -> etc...

function TreeNode(val) {
    this.val = val;
    this.left = this.right = null;
}
var sum = function(root) {
    console.log(root);
    if(root === null) return 0;
    return root.val + sum(root.left) + sum(root.right);
}

let tree = new TreeNode(1);
tree.left = new TreeNode(2);
tree.right = new TreeNode(3);
tree.left.right = new TreeNode(4);
let x = sum(tree);
console.log(x);

Basically, I want to console.log() the name of the variable rather than root in the sum function.

Basically, I want to console.log() the name of the variable rather than root in the sum function.

You can't. When your sum function is called, it is passed a value. That value is a pointer to an object and there is no connection at all to the variable that the pointer came from. If you did this:

let tree = new TreeNode(1);
let x = y = tree;
sum(x);
sum(y);

there would be no difference at all in the two calls to sum() . They were each passed the exact same value (a pointer to a TreeNode object) and there is no reference at all to x or y or tree in the sum() function.

If you want extra info (like the name of a variable) for debugging reasons and/or logging, then you may have to pass that extra name into the function so you can log it.

You can change the sum function for debugging purposes:

function sum(root, path) {
  if(!path) {
    path = 'root';
  }
  console.log(path);
  if(root === null) return 0;
  return root.val + sum(root.left, path+'.left') + sum(root.right, path+'.right'); 
}

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