Ionic Array bug?


#1

Hi!

I used an object to fill an array.

array = []
obj = {
index:0,
isOnline:false
}
for(let i =0;i<5;i++)
{
   obj.index = i;
   obj.isOnline = false;
   array.push(obj);
}

But the array is fill with:

array[0] = {index:4,isOnline:false}
array[2] = {index:4,isOnline:false}
array[3] = {index:4,isOnline:false}
array[4] = {index:4,isOnline:false}

Why is that happening?


#2

Your obj is defined outside the for loop. You push the same object all the time and change it too.

Create a new object inside the loop.

Push({index:i, isOnline: false})