Objects and Console.log: An Oddity Unraveled
When working with objects and console.log, you may encounter peculiar behavior. Let's unravel this mystery by analyzing this code snippet:
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 unexpected 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]
The Asynchronous Examination
The key to understanding this behavior lies in the asynchronous nature of object examination via console.log. While the console receives a reference to the object synchronously, it does not display its properties until you expand it manually.
The Instance Variable Surprise
When you expand an object after it has been modified, you see the updated values instead of the original state. This occurs asynchronously, leading to the seemingly illogical output.
Debugging Techniques
To avoid this inconsistency, consider these debugging techniques:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3