How to console log the name of a variable/function?

后端 未结 6 1446
梦谈多话
梦谈多话 2020-12-09 12:58

I want to do this: log(variableOrFunction)

And be able to produce this: variableOrFunction: actualValue.

I tried this:



        
相关标签:
6条回答
  • 2020-12-09 13:18

    You can’t achieve this within the JS interpreter the way you have described. There is no way to get the name of a variable inside of your log function.

    You can only do it inside of the caller of your log function, by converting the calling function to a string and parsing the code and grabbing the variable name passed to your log function.

    You could try to get the caller of the log function and do what I have described but I would not recommend this.

    0 讨论(0)
  • 2020-12-09 13:31

    If “value” is of type Object. You can try console.dir(value) instead of the long console.log, and you should be able to see the Object tree key: value pairs in a better formate in the console

    0 讨论(0)
  • 2020-12-09 13:33

    You can log them with a pair of braces around them ({}), which will create an object with the name of the variable as the key:

    function someFunction() {};
    
    const someOtherFunction = () => {};
    
    const someValue = 9;
    
    console.log({someFunction});
    console.log({someOtherFunction});
    console.log({someValue});
    
    const renamed = someFunction;
    
    console.log({renamed})

    0 讨论(0)
  • 2020-12-09 13:35

    Would this work for you?

    const log = function() {
      const key = Object.keys(this)[0];
      const value = this[key];
      console.log(`${key}:${value}`);
    }
    
    let someValue = 2;
    
    log.call({someVlaue}); //someValue:2
    

    Works with function too, even itself.

    log.call({log});
    
    // It would return the following
    log:function() {
      const key = Object.keys(this)[0];
      const value = this[key];
      console.log(`${key}:${value}`);
    }
    
    0 讨论(0)
  • 2020-12-09 13:36

    The "value" is of type Object. Use JSON.stingify to see in details,

    export const log = (value) => {
      console.log('' + value + ':', JSON.stringify(value))
      console.log(JSON.stringify(value))
    }
    
    0 讨论(0)
  • 2020-12-09 13:37

    Built on @CRice answer:

    const arr = [10, 20, 30, 40, 50]
    const obj = { a: 10, b: 20, c: 30, d: { e: 40 } }
    const str = "abcdef"
    
    function slog(obj) {
      Object.entries(obj).forEach(([key, value]) => console.log(key + ":", value))
    }
    
    slog({ arr })  // arr: [ 10, 20, 30, 40, 50 ]
    slog({ obj })   // obj: { a: 10, b: 20, c: 30, d: { e: 40 } }
    slog({ str })   // str: abcdef
    
    0 讨论(0)
提交回复
热议问题