Ajay kumar soni
Ajay kumar soni

Reputation: 19

Repeat the array element two times in JavaScript

I was writing a code in JavaScript to just repeat the array element two times. Here is my code.

var arr = [1,2];
for(var i=0;i!=arr.length;i++)
{
  arr.push(arr[i]);
}

for(var i=0;i!=arr.length;i++)
{
  console.log(arr[i]);
}

For example for arr =[1,2 ] output should be [1,2,1,2];

But I am getting error as:FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory

Upvotes: 1

Views: 222

Answers (1)

jabaa
jabaa

Reputation: 6741

arr.length grows while you're pushing new elements into the array. You can store the length in a separate variable:

const arr = [1, 2];
for(let i = 0, length = arr.length; i != length; ++i)
{
  arr.push(arr[i]);
}

for(let i = 0; i != arr.length; ++i)
{
  console.log(arr[i]);
}

Upvotes: 4

Related Questions