Home > Web Front-end > JS Tutorial > Why Does Chrome's JavaScript Console Show Only the Final Value of a Modified Array?

Why Does Chrome's JavaScript Console Show Only the Final Value of a Modified Array?

Patricia Arquette
Release: 2024-12-22 09:48:43
Original
713 people have browsed it

Why Does Chrome's JavaScript Console Show Only the Final Value of a Modified Array?

Chrome's JavaScript Console Exhibits Unexpected Object Evaluation

In a comparison between Firefox and Chrome JavaScript consoles, a peculiar behavior emerged. While Firefox accurately prints the initial value and subsequent modification of an array, Chrome displays only the modified value for both instances.

Problem:

The following code illustrates the issue:

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

Firefox's console produces the expected output:

["hi"]
["bye"]
Copy after login

However, Chrome's console renders:

["bye"]
["bye"]
Copy after login

Answer:

This behavior is due to a known and now fixed bug in Webkit: https://bugs.webkit.org/show_bug.cgi?id=35801. It involves the console's lazy evaluation of objects.

Lazy evaluation means the console does not evaluate an object until it is ready to display the output. This happens even if the object was modified before the console became active.

Solution:

To avoid this issue, one can convert the object to a string representation before logging it:

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

This forces the evaluation of the object immediately, and the console outputs:

hi
bye
Copy after login

The above is the detailed content of Why Does Chrome's JavaScript Console Show Only the Final Value of a Modified Array?. 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