Get variable names with JavaScript

前端 未结 7 959
傲寒
傲寒 2021-02-08 18:47

I want to create a log function where I can insert variable names like this:

var a = \'123\',
    b = \'abc\';

log([a, b]);

And the result sho

7条回答
  •  鱼传尺愫
    2021-02-08 19:17

    I know you want to save some keystrokes. Me too. However, I usually log the variable name and values much like others here have already suggested.

    console.log({a:a, b:b});
    

    If you really prefer the format that you already illustrated, then you can do it like this:

    function log(o) {
        var key;
        for (key in o) {
            console.log(key + ":", o[key]);
        }
    }
    
    var a = '1243';
    var b = 'qwre';
    log({
        a:a,
        b:b
    });
    

    Either way, you'd need to include the variable name in your logging request if you want to see it. Like Gareth said, seeing the variable names from inside the called function is not an option.

提交回复
热议问题