prototypal inheritance - How to prototype a duplicate prototype method for Array in javascript -


i'm trying implement duplicate method js array prototype concats duplicate of array so:

[11,22,3,34,5,26,7,8,9].duplicate(); // [11,22,3,34,5,26,7,8,9,11,22,3,34,5,26,7,8,9] 

here's have, causes browser crash:

var array = [11,22,3,34,5,26,7,8,9];  array.prototype.duplicate = function() {    var j = this.length;    for(var = 0; < this.length; i++) {     this[j] = this[i];     j++;   }    return this; } 

i'm trying using native js practice iterations , algorithms i'm trying avoid built-in methods, if possible, can clearer understanding of how things being moved around.

any ideas on why crashing , how can optimize it?

the code inside loop changes length of array, keep growing , never reach end of it. initial length of array in variable , use in loop condition. can use offset target index instead of counter:

var array = [11,22,3,34,5,26,7,8,9];  array.prototype.duplicate = function() {    var len = this.length;    (var = 0; < len; i++) {     this[len + i] = this[i];   }    return this; } 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -