JavaScript – duplicating array doesn't work

  • A+
Category:Languages

I am tring to make an array with duplicate elements. For example:

var myArray = ["one", "two", "five"]; 

when I'm looping through the for loop:

for(var i = 0; i < myArray.length; i++){   myArray.push(myArray[i]); } 

my browser crashes! I don't get any meaningful error. Could someone explain why is this happening?

 


Your for loop never ends, because the length is increasing for every iteration.

For getting only one copy, you could store the length in advance and loop only this length.

var myArray = ["one", "two", "five"];  for (var i = 0, l = myArray.length; i < l; i++){     myArray.push(myArray[i]); }  console.log(myArray);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: