How can I make console.log show the current state of an object?

前端 未结 11 1774
走了就别回头了
走了就别回头了 2020-11-22 00:28

In Safari with no add-ons (and actually most other browsers), console.log will show the object at the last state of execution, not at the state when conso

相关标签:
11条回答
  • 2020-11-22 01:22

    Simply refresh the page after you open the console or open the console before you submit the request to the targeted page....

    0 讨论(0)
  • 2020-11-22 01:24

    What I usually do if I want to see it's state at the time it was logged is I just convert it to a JSON string.

    console.log(JSON.stringify(a));
    
    0 讨论(0)
  • 2020-11-22 01:24

    There is an option to use a debugger library.

    https://debugjs.net/

    Just include the script into your web page and put log statements.

    <script src="debug.js"></script>
    

    Logging

    var test = {a: true}
    log(test); // {a: true}
    test.a = false; 
    log(test); // {a: false}
    
    0 讨论(0)
  • 2020-11-22 01:27

    You might want to log the object in a human readable way:

    console.log(JSON.stringify(myObject, null, 2));
    

    This indents the object with 2 spaces at each level.

    How can I pretty-print JSON using JavaScript?

    0 讨论(0)
  • 2020-11-22 01:30

    That > Object in the console, isn't only showing the current state. It actually is deferring reading the object and it's properties until you expand it.

    For example,

    var test = {a: true}
    console.log(test);
    setTimeout(function () {
        test.a = false; 
        console.log(test);
    }, 4000);
    

    Then expand the first call, it will be correct, if you do it before the second console.log returns

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