Javascript Console Log reporting object properties incorrectly

后端 未结 1 1373
生来不讨喜
生来不讨喜 2020-11-27 08:28

This could be a problem with JS Fiddle, but I am using console.log() to print the values of a collection of objects.

First I initialize the object colle

相关标签:
1条回答
  • 2020-11-27 09:18

    The browser doesn't save the whole object when you call console.log(), just a reference to it. When you inspect it later, the browser will get the current version of the object.

    You can test this quite simple by appending a new element to the object.

    Call this at the end:

    var newAppData = {
        "2": {
            name: "a",
            age: 443
        }
    }
    

    In the console it'll show up as

    Object {0: Foo, 1: Foo}
    Object {0: Foo, 1: Foo, 2: Foo}
    

    but when you open the first log entry, you will see all three elements, so the browser inspects the current version.

    Demo: https://jsfiddle.net/n302nsbh/22/

    Solution 1

    To see the current version of an element of the object, directly refer to it with console.log(fooManager.objects[0]); This will output for your script:

    Foo {name: "a", age: 2}
    Foo {name: "a", age: 443}
    

    Demo: https://jsfiddle.net/n302nsbh/23/

    Solution 2

    Just found another nice solution at https://stackoverflow.com/a/7389177/1682509

    Use console.log(JSON.parse(JSON.stringify(fooManager.objects))); to get a browsable snapshot.

    Demo: https://jsfiddle.net/n302nsbh/24/

    0 讨论(0)
提交回复
热议问题