1

I'm newbie in js. I redefined push() method in Array Object like below..

Array.prototype.push = function(item) {
    this[this.length] = '[' + item + ']';
    return this;
};

var arr = new Array();
arr.push('my');
console.debug(arr);
console.debug(arr[0]);

arr.push('name');
console.debug(arr);
console.debug(arr[1]);

arr.push('is');
console.debug(arr);
console.debug(arr[2]);


// output

[] --> <1>
[my]
[] --> <2>
[name]
[] --> <3>
[is]

but I can't understand why <1>,<2>,<3> is empty.

Ickhyun Kwon
  • 1,675
  • 4
  • 13
  • 17
  • Are you debugging in chrome by any chance? See http://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays – Crescent Fresh Mar 25 '11 at 02:44

2 Answers2

1

If you remove the brackets being concatenated, it works.

jsFiddle.

It looks like push is called internally a bit, and this may be why it is not working.

Also, there shouldn't be any reason to re-implement push yourself.

alex
  • 479,566
  • 201
  • 878
  • 984
1

Try using console.debug(arr.join(',')); instead of console.debug(arr);.

As in this jsfiddle.

The output is now

[my]
[my]
[my],[name]
[name]
[my],[name],[is]
[is]

Tested on Chrome.

As for the strange behavior of debug.console() when printing arrays, I suspect that it also uses push() on arrays while building the output string. If, for example, you replace the '['+item+']' with '<<'+item+'>>' you get some whackiness in the Firebug console, as in this jsfiddle.

brainjam
  • 18,863
  • 8
  • 57
  • 82