Home > Web Front-end > JS Tutorial > Why Does `console.log()` Show Unexpected Object Values After Modification?

Why Does `console.log()` Show Unexpected Object Values After Modification?

Mary-Kate Olsen
Release: 2024-12-20 17:07:10
Original
791 people have browsed it

Why Does `console.log()` Show Unexpected Object Values After Modification?

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);
Copy after login

Alternatively, you can convert the object to a JSON string using JSON.stringify():

console.log(JSON.stringify(obj));
Copy after login

Another approach is to preserve the inspectability of objects by re-encoding them with JSON.parse():

console.log(JSON.parse(JSON.stringify(obj)));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template