Home > Article > Web Front-end > Does Console.log() Correctly Output Objects and Arrays in Google Chrome?
Console.log() Inconsistency with Objects and Arrays in Google Chrome
Console.log(), a debugging tool in Google Chrome, exhibits peculiar behavior when used with objects and arrays. This anomaly manifests when:
<code class="javascript">var test = [[2345235345,"test"]] console.log(test); test[0][0] = 1111111; // outputs: [[1111111,"test"]] var testb = {}; testb.test = "test"; console.log(testb); testb.test = "sdfgsdfg"; // outputs: {"testb":"test"} var testc = ["test","test2"]; console.log(testc); testc[0] = "sdxfsdf"; // outputs: ["test","test2"]</code>
Interestingly, this behavior is exclusive to Chrome; Firefox does not exhibit it. Additionally, if the code is stepped through line-by-line in the Chrome debugger, console.log() displays the correct values.
Origin of the Phenomenon
Further investigation revealed that this is a known bug that has been resolved in Webkit but not yet incorporated into Google Chrome. The bug was initially reported in March 2010 (https://bugs.webkit.org/show_bug.cgi?id=35801), and a fix was implemented in August 2012. However, it has not yet made it into Chrome.
Console State Impact
The behavior of console.log() is influenced by the state of the console window. If the console window is open at the time a script is loaded, console.log() will display the current value of arrays and objects. However, if the console window is closed and opened after the script has loaded, console.log() will display modified values, even if they were changed after the console.log() execution.
<code class="javascript">var greetings=['hi','bye']; console.log(greetings); setTimeout(function(){ greetings.push('goodbye'); },3000);</code>
If the above script is executed with the console window already open, console.log() will display two items. If the console window is closed and reopened after the page loads, console.log() will display three items, reflecting the array's modified state.
This peculiarity suggests a potential bug in Google Chrome's console.log() functionality, which remains unfixed in the current version of Chrome.
The above is the detailed content of Does Console.log() Correctly Output Objects and Arrays in Google Chrome?. For more information, please follow other related articles on the PHP Chinese website!