A case in point
var a = {
index: 1
}
console.log(a);
a.index++;
Copy the code
We might think that the result of printing is{a: 1}
, but the facts are as follows:
And you can see that it’s actually printed out{a: 1}
, but is displayed when expandedindex
The value of theta is 2. Why is that? And then we notice that there’s an exclamation mark in the result, so let’s mouse over and see what it is.This means that the value is calculated once, but it may change later, so why does this happen? The answer comes in the middle volume of the book JavaScript You Don’t Know:
There is no specification or set of requirements that specify how the console.* family of methods should work — they are not a formal part of JavaScript, but are added to it by the host environment (see the “Types and Syntax” section of this book). Therefore, different browsers and JavaScript environments can be implemented as they wish, which can sometimes lead to confusion.
In particular, under certain conditions, the console.log(…) of some browsers Incoming content is not output immediately. The main reason for this is that IN many programs (not just JavaScript), I/O is a very slow blocking part. So, (from a page /UI perspective) the browser can improve performance by asynchronously processing console I/O in the background, where the user may not even be aware of it happening.
We usually think of it as just executing to console.log(..) Statement to see a snapshot of the a object, print something like {index: 1}, and then modify it when the next statement a.id ++ is executed strictly after the output of A. For the most part, the object representation that the preceding code outputs in the developer tools console is as expected. However, while this code is running, the browser may think it needs to defer console I/O to the background, in which case a.index++ may have been executed by the time the browser console outputs the object’s contents, thus displaying {index: 2}.
Exactly when console I/O is delayed, or even if it can be observed, is fluid. So if you encounter an object in console.log(..) during debugging The statement is later modified and you see unexpected results, be aware that this may be due to this I/O asynchrony.
So if this is the case, the best approach is a breakpoint, and the second-best approach is to serialize the object and force a snapshot, such as json.stringify
In this case, console.log prints a snapshot {index: 1}, which will be reevaluated when we expand the object. The value has already been changed, so we get the latest value {index: 2}.