2009
07.30

In real world applications, there are instances where the data structure of an object looks like an array.

var obj = {
 0: 'apple',
 1: 'orange',
 2: 'crab',
 length: 3
};
 
var ary = ['apple', 'orange', 'crab'];
 
alert(obj[0]); // apple
alert(ary[0]); // apple
 
alert(obj.length); // 3
alert(ary.length); // 3

They share some similarities, and, for debugging purposes (in Firebug), it’s sometimes beneficial display these special type of Objects as Arrays. Here’s how to do it.

// using the example above
var obj = {
  0: 'apple',
  1: 'orange',
  2: 'crab',
  length: 3,
  push: Array.prototype.push,
  slice: Array.prototype.slice,
  splice: Array.prototype.splice
};
 
if (this.console && console.log)
  console.log(obj); // ['apple', 'orange', 'crab'];

You can include other Array prototypes but push, slice and splice are the bare minimum to trick Firebug.

Note: The Objects are not converted to Arrays. I believe Firebug uses duck-typing to detect Arrays when displaying them on the console.

Updated: I guess my guess is correct, below is the proof.

// using the example above
var obj = {
  0: 'apple',
  1: 'orange',
  2: 'crab',
  length: 3,
  push: function(){},
  slice: function(){},
  splice: function(){}
};
 
if (this.console && console.log)
  console.log(obj); // ['apple', 'orange', 'crab'];

Update 2: Looking at the Firebug source that Tobie Langel provided in the comment below, we only need to include splice.

// using the example above
var obj = {
  0: 'apple',
  1: 'orange',
  2: 'crab',
  length: 3,
  splice: function(){}
};
 
if (this.console && console.log)
  console.log(obj); // ['apple', 'orange', 'crab'];

2 comments so far

Add Your Comment
  1. You’re right in your duck-typing assumption, as the source code indicates.

  2. @Tobie Thanks, I was able to simplify the code after viewing the source.