Assign console.log value to a variable

后端 未结 5 647
青春惊慌失措
青春惊慌失措 2020-12-25 13:56

How can I assign a JavaScript object to a variable which was printed using console.log?

I am in Chrome console. With Ruby I would use test = _

相关标签:
5条回答
  • 2020-12-25 14:17

    In Chrome developer tools, you may access last item by $_:

    > 1+1;
      2
    > $_
      2
    
    0 讨论(0)
  • 2020-12-25 14:18

    You could override standard console.log() function with your own, adding the behaviour you need:

    console.oldLog = console.log;
    
    console.log = function(value)
    {
        console.oldLog(value);
        window.$log = value;
    };
    
    // Usage
    
    console.log('hello');
    
    $log // Has 'hello' in it
    

    This way, you don't have to change your existing logging code. You could also extend it adding an array and storing the whole history of printed objects/values.

    0 讨论(0)
  • 2020-12-25 14:32

    Here is chrome reference for comand line api. There is $_ variable but it "Returns the value of the most recently evaluated expression" not printed, you can make your own log function like this:

    function log(data){
       console.log(data);
       return data;
    }
    // after that you can access last printed value by $_
    

    Please, note that my function is for example, console.log possibilities is much more advanced

    0 讨论(0)
  • 2020-12-25 14:39

    Derivative of mirrormx's answer, but more convenient. I don't need to write a function and can just put it in anywhere on the spur of the moment.

    console.log(window.$log = data);
    
    0 讨论(0)
  • 2020-12-25 14:41

    If you want to do this to an object that has been already logged (one time thing), chrome console offers a good solution.

    Hover over the printed object in the console, right click, then click on "Store as Global Variable". Chrome will assign it to a temporary var name for you which you can use in the console.

    0 讨论(0)
提交回复
热议问题