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"
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!