Reputation: 19
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
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