The Perplexing Behavior of Objects and console.log
When utilizing the console.log() function to examine objects, you may encounter peculiar results. For instance, if you log an array of objects and then modify it using splice(), you'll observe that the console still displays the original array.
Why This Occurs
Console.log inspects objects asynchronously. Although the console synchronously retrieves a reference to the object, it defers displaying its properties until after you expand it (this behavior varies across browsers). Consequently, if the object is altered before inspection, the displayed data will contain the updated values.
Identifying the Discrepancy
Chrome provides a visual cue to alert you to this behavior. A small "i" appears in a box when you hover over the object, displaying this message: "Object value at left was snapshotted when logged, value below was evaluated just now."
Addressing the Issue
To avoid this discrepancy, consider logging individual object property values:
console.log(obj.foo, obj.bar, obj.baz);
Alternatively, you can convert the object to a JSON string using JSON.stringify():
console.log(JSON.stringify(obj));
Another approach is to preserve the inspectability of objects by re-encoding them with JSON.parse():
console.log(JSON.parse(JSON.stringify(obj)));
However, note that JSON removes nonserializable properties such as functions and DOM elements. For complex objects, employ a robust deep copy mechanism to preserve such properties.
The above is the detailed content of Why Does `console.log()` Show Unexpected Object Values After Modification?. For more information, please follow other related articles on the PHP Chinese website!