console.log inconsistent with JSON.stringify

前端 未结 2 1622
孤独总比滥情好
孤独总比滥情好 2021-02-20 18:11

I have reason to believe console.log and JSON.stringify can produce inconsistent views of the same object even if it was created in a straightforward m

相关标签:
2条回答
  • 2021-02-20 18:37

    Why don't you just use console.dir(obj) instead? Or use console.log(obj) and then click on the output / expand it?

    Also when I try the following code:

    var obj = {};
    obj.players = {};
    obj.players[0] = {color: "green"};
    obj.players[1] = {color: "blue"};
    obj.world = "xyz";
    console.log(JSON.stringify(obj));
    

    I always (Firefox, Chrome, Opera) get this as output:

    {"players":{"0":{"color":"green"},"1":{"color":"blue"}},"world":"xyz"}
    

    Furthermore it looks like your players object is actually an array. So you should better create it as such.

    Update: I just saw that you added a link to a JSFIDDLE demo, which empties the players object right after logging it. To my knowledge all web dev tools use some kind of asynchronous display, which results in an empty players object when using console.log(obj) or console.dir(obj). Firebug thereby offers the best results by displaying the object correctly using console.dir(obj).

    0 讨论(0)
  • 2021-02-20 18:55

    To answer the question - yes, console.log operations are asynchronous so can't be relied upon to print accurate values in the console - especially if you modify the printed object straight after the console.log call (like you are doing).

    If you take away the line:

    obj.players = {};
    

    then both the differences between the plain console.log and the JSON.stringify dissappear.

    Bearing in mind that there is a difference between logging a real object in a developer tools console (console.log(obj) and printing the stringified version of the object (console.log(JSON.stringify(obj))). So the representation of the object will still be different.

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