In Safari with no add-ons, console.log
will show the object at the last state of execution, not at the state when console.log
was called.
I have to clone the object just to output it via console.log
to get the state of the object at that line.
Example:
var test = {a: true}
console.log(test); // {a: false}
test.a = false;
console.log(test); // {a: false}
I think you're looking for
console.dir()
.console.log()
doesn't do what you want because it prints a reference to the object, and by the time you pop it open, it's changed.console.dir
prints a directory of the properties in the object at the time you call it.The JSON idea below is a good one; you could even go on to parse the JSON string and get a browsable object like what .dir() would give you:
console.log(JSON.parse(JSON.stringify(obj)));
I defined an utility:
and when I want to log on console I simply do:
It works very well!
Simply refresh the page after you open the console or open the console before you submit the request to the targeted page....
There is an option to use a debugger library.
https://debugjs.net/
Just include the script into your web page and put log statements.
Logging
Vanilla JS:
@evan's answer seems best here. Just (ab)use JSON.parse/stringify to effectively make a copy of the object.
JQuery specific solution:
You can create a snapshot of an object at a certain point in time with
jQuery.extend
What is actually happening here is jQuery is creating a new object with the
test
object's content, and logging that (so it will not change).AngularJS (1) specific solution:
Angular provides a
copy
function that can be used to the same effect:angular.copy
Vanilla JS wrapper function:
Here is an function which wraps
console.log
but will make a copy of any objects before logging them out.I wrote this in response to a few similar but less robust functions in the answers. It supports multiple arguments, and will not try to copy things if they are not regular objects.
example usage:
consoleLogWithObjectCopy('obj', {foo: 'bar'}, 1, /abc/, {a: 1})
using Xeon06's hint, you may parse his JSON in an object, and here is the log function I now use to dump my objects :