2

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?

2
  • 2
    Every call to .push() increases myArray.length by 1. Commented Nov 3, 2018 at 12:28
  • Thanks a lot I've solved it using concat, but I wanted to understand why does it happen :) Commented Nov 3, 2018 at 12:34

4 Answers 4

7

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);

Sign up to request clarification or add additional context in comments.

Comments

6

When you use add items to the array, the length grows, which makes the for loop add more items, which increase the length, and so on...

A simple solution is to concat the array to itself:

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

var result = myArray.concat(myArray);

console.log(result);

Or push all the items at once using spread, if you want to mutate the array:

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

myArray.push(...myArray);

console.log(myArray);

Comments

2

If you change myArray.length to a constant number, this problem does not happen. However, the reason for the crashing is every call to .push() increases your array length by 1 anyway, I think this crash is interesting and could be an unhandled bug maybe!

var myArray = ["one", "two", "five"];
var l=myArray.length;
for(var i = 0; i < l; i++){// for example l=3 here
  myArray.push(myArray[i]);

}

Comments

2

An ES6 solution would be use the spread operator. Which behaves like a concat.

let myArray = ["one" ,"two","five"];
myArray = [ ...myArray, ...myArray];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.