1

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

5
  • 1
    After you push into an array its length grows. Commented Nov 10, 2021 at 16:20
  • 2
    As is often the case, if you step through the code in the debugger, looking at the values of things and how the code moves from statement to statement, the reason becomes clear. More: How to debug small programs. Debugging is not an advanced skill. It's basically the next thing you should learn about after "Hello, world." Commented Nov 10, 2021 at 16:21
  • 4
    btw, one line alternative arr = [...arr, ...arr] Commented Nov 10, 2021 at 16:23
  • 1
    What's your question? Why you get the error? Or are you asking how to do it in other ways? Please always be sure to be clear and focused about the question you're actually asking. Commented Nov 10, 2021 at 16:29
  • Any other solution such as using arr.concat, or spread syntax is getting downvoted, not sure why. Commented Nov 10, 2021 at 16:40

1 Answer 1

4

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

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

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.