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.
-
Are you debugging in chrome by any chance? See stackoverflow.com/questions/4057440/…Crescent Fresh– Crescent Fresh2011年03月25日 02:44:41 +00:00Commented Mar 25, 2011 at 2:44
2 Answers 2
If you remove the brackets being concatenated, it works.
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.
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.