I just stumbled upon this while deleting an object in an array.
Here is the code:
friends = [];
friends.push(
{
a: 'Nexus',
b: 'Muffin'
},
{
a: 'Turkey',
b: 'MonkMyster'
}
)
console.log(friends);
for(i in friends){
if(friends[i].a == 'Nexus'){
delete friends[i];
friends.push({
a: 'test',
b: 'data'
});
}
}
console.log(friends);
It is posted on jsfiddle as well.
Basically, why does my first console.log
of friends
output:
[Object, Object]
But, when deleting that object in the loop and then adding a new object to the array, it logs:
[1: Object, 2: Object]
What exactly does 1:, 2:
mean (obviously to associate for each object), but I wonder why it's not there after the first logging of friends
? Is my object notation in my friends array wrong? I feel like I'm creating the initial friends
array wrong and the JavaScript parser is correcting me?
Because you deleted the first item (without reindexing) and pushed a new one.
Initially, you had an array with an object at its 0th position, and another one at the 1st one.
After the change, you have an array with an object at the 1st position, and another one at the 2nd one.
Therefore, the console just wants to show that the first entry is at the 1st position instead of at 0th one.
Each console may do this differently, for example on Firefox I get
Array [ <1 empty slot>, Object, Object ]
The console is just a debugging tool, you can just ignore those syntaxes. You are not doing anything wrong.
However, using sparse arrays may be a bit odd. You can consider reindexing the array instead of just deleting the property:
delete array[position]; // Just remove
array.splice(position, 1); // Remove and reindex
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With