Asynchronous Behavior of Objects in Console.log
When examining objects using console.log, it's important to be aware of its asynchronous nature. Console receives an object reference synchronously but displays its properties only when it's expanded. This can lead to discrepancies if the object is modified before it's examined.
Consider the following code:
foo = [{id: 1},{id: 2},{id: 3},{id: 4}, {id: 5}, ]; console.log('foo1', foo, foo.length); foo.splice(2, 1); console.log('foo2', foo, foo.length);
In Chrome, this produces the following output:
foo1 [Object, Object, Object, Object, Object] 5 0: Object 1: Object 2: Object 3: Object length: 4 __proto__: Array[0] 5 (index):23 foo2 [Object, Object, Object, Object] 4 0: Object 1: Object 2: Object 3: Object length: 4 __proto__: Array[0]
Initially, console.log receives a reference to the object foo. However, the properties are displayed later, after the object has been modified by foo.splice(2, 1). Hence, the output shows the updated values.
To mitigate this issue, there are several alternative logging approaches:
console.log(foo.id, foo.name, foo.age);
console.log(JSON.stringify(foo));
console.log(JSON.parse(JSON.stringify(foo)));
These methods ensure that the logged output reflects the state of the object at the time of logging.
The above is the detailed content of Why Does `console.log` Show Asynchronous Object Behavior?. For more information, please follow other related articles on the PHP Chinese website!