Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Chrome console isn't displaying array-like objects correctly when their indexers are get/set based?

Part of the ECMA standard I believe is that Javascript consoles will display objects as arrays when the objects are array-like.

Such as: ["hello", "world"] for an object containing strings that are numerically indexed.

Array-like behaviour is defined as a length property and a splice method being present on the object, as well as numerically indexed properties.

Many of us have probably seen this with jQuery in the past.

I've been trying to take advantage of this behaviour and consider it desirable. However I have the additional requirement that my indexes use getters/setters to set them so that I can do some additional processing when they're modified.

However when I do this the above array is instead rendered as:

[undefined × 2]

However the object behaves otherwise exactly the same as a simple example.

See this Fiddle for a far better explanation: http://jsfiddle.net/5YgAv/

So you see? Two very similar examples, however the presence of the getter has broken it in the console.

I've been debugging the latest Chromium source code and it appears that Chrome pushes a message at the console which essentially contains the getter function. However there's no way to modify the console source code so that it can invoke the function and get the value. If that were possible then we could modify the developer tools to handle getters and setters correctly.

What I'd like to know is if anyone has any insight into this interesting little bug or how it might be best fixed before I file it as a bug with the Chrome team to be long forgotten and buried in the depths of Google. I'd actually quite like to fix this myself one way or another.

I'm also open to a workaround that's elegant and allows me to do some special processing when any of the properties on my array-like object are modified.

Help me Obi-Stackoverflow-Kenobi, you're my only hope!

[Ryan]

like image 976
Ryan Worsley Avatar asked Jul 04 '12 07:07

Ryan Worsley


1 Answers

While this doesn't answer the question of WHY Chrome won't write out your array like an array, there is a way to "trick" Chrome into doing it. Luckily for us, it's super simple.

  1. Overwrite the toString function of your object, returning your data variable
  2. When you log your array, log it as myArray.toString();

See this jsFiddle: http://jsfiddle.net/YXwxS/

In the meantime, I'm going to keep researching this because it's an interesting problem :)

like image 108
Jason L. Avatar answered Sep 28 '22 02:09

Jason L.