Home > Web Front-end > JS Tutorial > Why Does Chrome's JavaScript Console Show Modified Object Values Instead of Original Values?

Why Does Chrome's JavaScript Console Show Modified Object Values Instead of Original Values?

Susan Sarandon
Release: 2024-12-24 03:20:18
Original
294 people have browsed it

Why Does Chrome's JavaScript Console Show Modified Object Values Instead of Original Values?

Chrome's JavaScript Console Evaluation Behavior for Objects

Question:

In a JavaScript code snippet, an array is defined and printed to the console. After modifying the array's element, it is printed again. Firefox's console displays both correct values, but Chrome's console lazily evaluates the object and prints the modified value for both instances.

Is there an error in the code or is it a Chrome console behavior?

Answer:

As pointed out in a WebKit bug report (now fixed), there is an issue regarding Chrome's evaluation of objects in the console.

Explanations and Avoidance:

This behavior stems from the lazy evaluation nature of Chrome's console for objects. It evaluates them only when they are displayed on the console, leading to incorrect output if the object is modified before the display.

To avoid this issue, one can call .toString() on the object, which creates a representation that will not be altered by subsequent code changes. Calling .toString() before printing to the console ensures that the correct values are displayed.

Modified Code:

var s = ["hi"];
console.log(s.toString()); // Prints "hi"
s[0] = "bye";
console.log(s.toString()); // Prints "bye"
Copy after login

Using this modified approach, the console output in Chrome will be identical to that in Firefox, displaying both correct values for the array.

The above is the detailed content of Why Does Chrome's JavaScript Console Show Modified Object Values Instead of Original Values?. 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