简体   繁体   中英

Weird behaviour in chrome object console.log

When I try to console.log an object in Chrome, it states in the first line of the console.log (where you see Object { small summary here } that my posts array is of length 0 (posts: Array[0]).

However when I expand the post it shows that it has 27 items in it (which is what I need).

This happens to me randomly and I got no idea why it is happening, anybody experienced this before?

Screenshot: 截图

Update: This happens in all browsers, so it is probably not chrome related

The debugger can't know if an object has been altered, this is why the posts attribute's rendering (in your example) has not been updated. Even if the debugger would be able to know when a attribute has been changed updating it every time (and all "loggings") would be too expensive.

So the debugger will check the attribute only when accessing it explicitly.

Chrome in this case will do this even only once:

p = []; window.x = {x: p}; 
Object {x: Array[0]}
x: Array[0]
__proto__: Object
x.x.push(1);
1
x.x.push(2);
2

Klicking x , the Array updates

p = []; window.x = {x: p}; 
Object {x: Array[2]}
x: Array[2]
   0: 1
   1: 2
   length: 2
   __proto__: Array[0]
__proto__: Object

Adding one item more to the array and toggleing x again, the size and entries remain

x.x.push(3)
3


x: Array[2]
   0: 1
   1: 2
   length: 2
   __proto__: Array[0]

In my opinion it's not necessary for the logger to update the object value since the variable watch has this function already. There you can always update the current value of a variable.

This works in Firebug and Chrome. Here's an example for Chrome:

Chrome:如何在调试器监视中更新变量

The answer of "try-cache-finally" is correct too but I want to contribute the answer that caused the problem to happen in the first place.

when you have this code:

var b = [];
function a(callback) {
   if (b.length > 0) {
       return callback();
   }

   doXhr(function() {
       b.push("something");
   })
}

when you now call a twice then the second call will not see the updated a because of the XHR requests still being in process, this causes the xhr request to be called twice.

The solution for this is to wait on the callback for a like this:

a(function() {
    a(function() {
        // Correct trigger
    });
});

So actually basic async programming, but this error was because of an already existing code base with this bug in it and it was hard to track down.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM